首页 > 解决方案 > Python:第 3 级嵌套列表理解未按预期运行

问题描述

我正在尝试为字符“a”、“b”和“c”获取长度为 1、2 和 3 的所有可能排列

from itertools import permutations

a = ['a','b', 'c']
perm1 = permutations(a, 1)
perm2 = permutations(a, 2)
perm3 = permutations(a, 3)
p_list = []
p_list.extend(list(perm1))    
p_list.extend(list(perm2))
p_list.extend(list(perm3))

str = [[j for j in i] for i in p_list]

print(str[3])

在这一点上,事情是预料之中的

当我str = line 对此进行修改时,str = [[[''.join(k) for k in j] for j in i] for i in p_list] 我希望得到一个字符串列表,其中每个排列都是一个没有逗号的字符串。例如 ["abc", "a", "b", "c"] 等,但我得到了一个列表列表。

标签: pythonlist-comprehension

解决方案


第一件事:请不要设置str为变量。

下面我复制了你的代码,评论了它的p_list样子。

from itertools import permutations

a = ['a','b', 'c']
perm1 = permutations(a, 1)
perm2 = permutations(a, 2)
perm3 = permutations(a, 3)
p_list = []
p_list.extend(list(perm1))    
p_list.extend(list(perm2))
p_list.extend(list(perm3))

# p_list = [('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

如您所见,您的数据结构不是第 3 级:它只是一个元组列表。现在我认为很明显,您的列表理解只是迭代元组中的每个元素而不是像这样加入它们:

result = [''.join(n) for n in p_list]
# result = ['a', 'b', 'c', 'ab', 'ac', 'ba', 'bc', 'ca', 'cb', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba']

推荐阅读