python - 根据列表中每个元组的长度克隆列表中的元组

标签 python python-2.7 list tuples

我有以下元组列表:

indices = [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

我正在运行以下命令并获得:

indices2 = []
for j in range(len(indices)):
    indices2.append(indices[j] * len(indices[j]))
indices2

给出:

[(1,), (2,), (3,), (1, 2, 1, 2), (1, 3, 1, 3), (2, 3, 2, 3), (1, 2, 3, 1, 2, 3, 1, 2, 3)]

但是,我想获得:

[(1,), (2,), (3,), (1, 2), (1, 2), (1, 3), (1, 3), (2, 3), (2, 3), (1, 2, 3), (1, 2, 3),
(1, 2, 3)]

我哪里做错了?

最佳答案

您可以先创建一个嵌套列表的列表,然后在 for 循环之后将其展平:

import itertools

indices = [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

indices2 = []
for j in range(len(indices)):
    indices2.append([indices[j]]*len(indices[j]))

chain = itertools.chain(*indices2)
indices2 = list(chain)
print indices2

[indices[j]]*len(indices[j]) 创建列表,每个列表具有 len(indices[j]) 数量的 indices[j ] 元组。然后使用 itertools.chain 将生成的嵌套列表 indices2 展平为单个非嵌套列表。

另一种方法是嵌套的 for 循环:

indices2 = []
for j in range(len(indices)):
    for jln in range(len(indices[j])):
        indices2.append(indices[j])

这里的循环简单地附加元组 len(indices[j]) 时间。

第一个可能更 pythonic,看起来更好,第二个更简单。如果问题需要性能升级,第一个也可能有更多的开销,应该对此进行验证。

关于python - 根据列表中每个元组的长度克隆列表中的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373200/

相关文章:

javascript - 使用 Pyjs 将 python 脚本转换为 javascript 代码

Python:如何创建由随机数组成的长度递增的列表列表?

python - 在 Python 中总结字符串列表

python - 获取符合条件的列表的百分比

python - EEG 信号的带宽

python - 尝试格式化并打印列表中的多个(动态)字典

python-2.7 - 如何从 sqlalchemy 获取列名?

python - 从Python子线程接收数据的简单方法

python - 在 Python 中绘制曲线

python - 漂亮的 Python 打印机?