我需要生成每个字符串列表中每个元素的所有可能组合。
list1 = ['The girl', 'The boy']
list2 = ['wears', 'touches', 'tries']
list3 = ['a red sweater', 'a blue sweater', 'a yellow sweater', 'a white sweater']因此,结果是将每个元素组合在一起的字符串列表:
The girl wears a red sweater
The boy wears a red sweater
The girl touches a red sweater
The boy touches a red sweater
The girl wears a blue sweater
The boy wears a yellow sweater
(ETC...)只要得到所有的组合,我就不会特别关心输出的顺序。
从我的研究中,我猜“置换”将是一个解决方案,但我只找到了几个关于数字列表排列或字符串中每个字母组合的答案。这些东西都不是我需要的。我需要合并在列表中排列的文本块。
如何创建一个包含每个字符串列表中不同元素的所有组合的长句子列表?
谢谢
发布于 2017-10-29 20:34:58
使用itertools的产品,其简单程度如下:
import itertools
["{x} {y} {z}".format(x=x,y=y,z=z) for x,y,z in itertools.product(list1, list2, list3)]在python3.6中,您可以删除format调用
[f"{x} {y} {z}" for x,y,z in itertools.product(list1, list2, list3)]发布于 2017-10-29 20:34:51
只要一堆简单的for循环就行了。诀窍是打印z,y,x的顺序。
list1 = ['The girl', 'The boy']
list2 = ['wears', 'touches', 'tries']
list3 = ['a red sweater', 'a blue sweater', 'a yellow sweater', 'a white sweater']
for x in list3:
for y in list2:
for z in list1:
print (z,y,x)产出;
The girl wears a red sweater
The boy wears a red sweater
The girl touches a red sweater
The boy touches a red sweater
The girl tries a red sweater
The boy tries a red sweater
The girl wears a blue sweater
The boy wears a blue sweater
The girl touches a blue sweater
The boy touches a blue sweater
The girl tries a blue sweater
The boy tries a blue sweater
The girl wears a yellow sweater
The boy wears a yellow sweater
The girl touches a yellow sweater
The boy touches a yellow sweater
The girl tries a yellow sweater
The boy tries a yellow sweater
The girl wears a white sweater
The boy wears a white sweater
The girl touches a white sweater
The boy touches a white sweater
The girl tries a white sweater
The boy tries a white sweater发布于 2017-10-29 20:34:51
使用itertools.product,笛卡尔产品的方便工具。然后join产品:
from itertools import product
lst = [' '.join(p) for p in product(list1, list2, list3)]
from pprint import pprint
pprint(lst)
['The girl wears a red sweater',
'The girl wears a blue sweater',
'The girl wears a yellow sweater',
'The girl wears a white sweater',
'The girl touches a red sweater',
'The girl touches a blue sweater',
'The girl touches a yellow sweater',
'The girl touches a white sweater',
'The girl tries a red sweater',
'The girl tries a blue sweater',
'The girl tries a yellow sweater',
'The girl tries a white sweater',
'The boy wears a red sweater',
'The boy wears a blue sweater',
'The boy wears a yellow sweater',
'The boy wears a white sweater',
'The boy touches a red sweater',
'The boy touches a blue sweater',
'The boy touches a yellow sweater',
'The boy touches a white sweater',
'The boy tries a red sweater',
'The boy tries a blue sweater',
'The boy tries a yellow sweater',
'The boy tries a white sweater']https://stackoverflow.com/questions/47004945
复制相似问题