迭代类型列表上的迭代类型转换

时间:2019-09-27 12:40:09

标签: python iterator list-comprehension itertools

我有这样的字符串列表:

names = ['Katia', 'Alexandre']

我想达到这个结果:

['Katia', 'Alexandre', 'Katia Alexandre', 'Alexandre Katia']

我需要所有尺寸为 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')]]

有人可以解释为什么这样的行为吗?

2 个答案:

答案 0 :(得分:2)

您可以使用' '.join方法将字符串元组连接到以空格分隔的字符串中:

def permutations_all_sizes(iterable):
    sizes = range(1, len(iterable)+1)
    permutations = [' '.join(permutation) for x in sizes for permutation in itertools.permutations(iterable, x)]
    return permutations

答案 1 :(得分:1)

您可以通过以下列表理解来获得所需的输出:

print([' '.join(names) for tup in perms for names in tup])

代码行为的说明:

names = ['Katia', 'Alexandre'],所以

sizes = range(1, len(iterable)+1) = range(1, 3),所以

permutations = [itertools.permutations(iterable, x) for x in sizes] =

= [itertools.permutations(iterable, 1), itertools.permutations(iterable, 2)

itertools.permutations(iterable, 1)包含长度为1的可迭代元素的元组:

names = ['Katia', 'Alexandre']
for something in itertools.permutations(names, 1):
    print(something)  # will print ('Katia',) then ('Alexandre',)

这样对这个置换对象执行list(tup)会得到一个像[('Catia',), ('Alexandre',)]这样的元组列表。

相同的逻辑适用于itertools.permutations(iterable, 2)

names = ['Katia', 'Alexandre']
for something in itertools.permutations(names, 2):
    print(something)  # will print ('Katia', 'Alexandre'), then ('Alexandre', 'Katia')

list(tup)将给出[('Katia', 'Alexandre'), ('Alexandre', 'Katia')]

将它们组合成列表理解[list(tup) for tup in perms]将得到以下结果:[[('Catia',), ('Alexandre',)], [('Catia', 'Alexandre'), ('Alexandre', 'Catia')]]

将列表理解修改为[list(tup) for tup in [iterator for iterator in perms]]不会执行任何操作:perms已经是列表,而[iterator for iterator in perms]等效于perms