python - 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"] 等,但我得到了一个列表列表。
解决方案
第一件事:请不要设置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']
推荐阅读
- oauth - 使用“授权代码授予”的 Netlify API 服务器到服务器 OAuth
- java - 如何从此多选微调器中获取价值并将其保存到字符串?
- rdf - 嵌套的 SKOS 概念方案?
- java - 使用单例设计模式时,其他方法是否需要使用synchronized关键字来保证线程安全?
- unity3d - 如何在运行时将 three.js(来自 blender 的 JSON)模型导入 Unity?
- vba - 根据类别将电子邮件移动到子文件夹
- android-studio - 如何仅使用 Android Studio git 插件 GUI 对齐 git 工作副本
- java - 如何修改此代码以处理包含字符和整数的输入文本?
- react-native - React Native iOS 应用程序在收到推送通知并且应用程序打开时崩溃
- python - 尝试使用 Numpy 检查圆内的点