初学者问题: 如果我有2个仅包含字符串的列表,如何将它们连接到包含所有元素+一个列表中的每个元素+另一个列表中的每个元素的第三个列表中?我考虑过for循环,但是没有更简单的方法吗? 示例:
listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']
resulting list = ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun', 'catbinsun', 'catsunbin', 'catcat', 'catdog', 'dogbin', 'dogcat']
编辑:谢谢大家的答复,但我没有解释我要做好的事情。 每个列表中的字符串数应该是不确定的,并且每个单词都必须与其他单词串联在一起,而不仅是“ x + y”形式。 我还想将其连接到其他词上。像u = x + y + z
答案 0 :(得分:2)
您可以使用笛卡尔积并加入。试试这个:
import itertools
listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']
listone + listtwo + list(''.join(e) for e in itertools.product(listone, listtwo))
结果:
['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']
答案 1 :(得分:2)
这应该可以完成
In [29]: import itertools
In [30]: listone = ['cat', 'dog' ]
...: listtwo = ['bin', 'sun']
In [31]: output = listone + listtwo + [ "".join(items) for items in list(itertools.product(listone, listtwo))]
In [32]: output
Out[32]: ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']
您也可以不使用itertools
In [33]: output = listone + listtwo + [ item_one+item_two for item_one in listone for item_two in listtwo]
In [34]: output
Out[34]: ['cat', 'dog', 'bin', 'sun', 'catbin', 'catsun', 'dogbin', 'dogsun']
答案 2 :(得分:0)
在不导入itertools的情况下,您也可以在访问listone
和listtwo
的元素时使用字符串连接,如下所示:
result = listone + listtwo + [listone[0] + listtwo[0], listone[0] + listtwo[1], listone[1] + listtwo[0], listone[1] + listtwo[1]]
答案 3 :(得分:0)
或者,如果您想手动操作,我会这样做:
l = ["a","b"]
l2 = ["c","d"]
l3 = l + l2
print(l3)
for x, y in zip(l,l2):
l3.append(x+y)
print(l3)
我不知道这是否是最佳选择。
答案 4 :(得分:0)
如果使用display server,则可以使用相对简单的代码获得此结果:
listone = ['cat', 'dog' ]
listtwo = ['bin', 'sun']
result_list = listone + listtwo + [x + y for x in listone for y in listtwo]
答案 5 :(得分:0)
如果您仅在寻找组合(即x + y,x + y + z,而不是y + x或z + y + x),则可以使用itertools中的combinations
函数来形成一个功率设定:
from itertools import combinations
words = listone+listtwo
result = ["".join(c) for r in range(1,len(words)+1) for c in combinations(words, r)]
print(result)
# ['cat', 'dog', 'bin', 'sun', 'catdog', 'catbin', 'catsun', 'dogbin',
# 'dogsun', 'binsun', 'catdogbin', 'catdogsun', 'catbinsun', 'dogbinsun',
# 'catdogbinsun']
注意:组合幂集随源项的数量呈指数增长:2 ^ n-1
如果要获取排列,请从itertools中将combinations
替换为permutations
。 (这将产生比组合更多数量级的元素)