簡體   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