【发布时间】:2026-02-13 21:30:01
【问题描述】:
我有这样一个字符串列表:
names = ['Katia', 'Alexandre']
我想达到这个结果:
['Katia', 'Alexandre', 'Katia Alexandre', 'Alexandre Katia']
i.e. 我需要大小 range(1, length(names)+1) 的所有排列。
我编写了这个函数来生成一个可迭代的列表:
import itertools
def permutations_all_sizes(iterable):
sizes = range(1, len(iterable)+1)
permutations = [itertools.permutations(iterable, x) for x in sizes]
return permutations
现在,我的想法是执行一个嵌套列表推导来解开字符串。但是,无论我是嵌套还是不嵌套,结果总是一样的:
perms = permutations_all_sizes(names)
[list(tup) for tup in perms]
[162]: [[('Catia',), ('Alexandre',)], [('Catia', 'Alexandre'), ('Alexandre', 'Catia')]]
[list(tup) for tup in [iterator for iterator in perms]]
[165]: [[('Catia',), ('Alexandre',)], [('Catia', 'Alexandre'), ('Alexandre', 'Catia')]]
有人可以解释为什么会出现这种行为吗?
【问题讨论】:
标签: python iterator list-comprehension itertools