繁体   English   中英

Python:第 3 级嵌套列表理解未按预期运行

[英]Python: 3rd level nested list comprehension not acting as expected

我正在尝试为字符“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"] 等,但我得到了一个列表列表。

第一件事:请不要将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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM