python - python 3.7 中 .append 函数的自动化

标签 python list

我有一个列表,其中包含不同长度的嵌套列表,范围从 3 到 105。我想基于该新列表进行创建,其中包含这些原始列表中所有对的组合,格式如下:来自 [7,5,6 ] 到 [7,5]、[7,6]、[5,6]

我使用了下面的代码,但是对于列表中的 105 个值来说这是不可行的。有没有一种算法可以自动化这个过程?

list3 = ([7,5,6], [6,9,7], [7,8,4], [2,4,6,7,9])
list4 = []
for sublist in list3:
    if len(sublist) == 3:
       list4.append([sublist[0], sublist[1])
       list4.append([sublist[0], sublist[2])
       list4.append([sublist[1], sublist[2])

最佳答案

您也许可以使用itertools.combinations()在给定最大范围的情况下帮助生成唯一的对集。

类似于:

from itertools import combinations
list3 = ([7,5,6], [6,9,7], [7,8,4], [2,4,6,7,9])
list4 = []
for sublist in list3:
    for (i, j) in combinations(range(len(sublist)), 2):
       list4.append([sublist[i], sublist[j]])

为了提高效率,我建议使用列表理解:

list4 = [[sublist[i], sublist[j]] for sublist in list3 for (i, j) in combinations(range(len(sublist)), 2)]

有关列表推导式与使用 for 循环附加到列表的更多信息:Why is a list comprehension so much faster than appending to a list?

<小时/>

正如 @chepner 在下面的评论中指出的,combinations 接受任何可迭代对象,因此您可以简单地将其用作 combinations 的输入。我们也不需要附加单独的元素。我们可以生成我们需要的组合,从而生成一个列表,并且我们可以将所有内容连接在一起:

list4 = [t for sublist in list3 for t in combinations(sublist, 2)]

关于python - python 3.7 中 .append 函数的自动化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56654547/

相关文章:

OCaml中具有特定长度的列表的列表

python - 如何在 python 函数中访问 double yield?

python - Tkinter 选项菜单

python - 在python中以xml格式返回sql查询

python - 我们可以从 py2exe 在 Python 中创建的可执行文件进行文件处理吗?

javascript - 在javascript中使用元组作为字典中的键

python - SciPy 曲线拟合参数的方差到底是多少? (Python)

python : extract parameters created with argparse

c++ - 删除列表中创建的对象

java - 使用 Integer foo(String s) 将 List<String> 转换为 List<Integer>