gpt4 book ai didi

python - 基于一个键属性的python中嵌套列表的组合

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:50 27 4
gpt4 key购买 nike

我不知道怎么形容。我举个例子:这是我的输入列表

[[0,25], [1,54], [2,76], [3,13], [4,79]]

这是我想要的输出:

[[[0,25], [1,54]], [[0,25], [1,54]], [[0,25], [2,76]], ...]

即我想要一个列表,其中包含基于内部列表的第一个字段一次取 2 个内部列表的所有组合。

我试过这样的 itertools:

perm_list = itertools.combinations(task_list, 10)

但它所做的只是显示:

itertools.combinations object at 0x0120B060

最佳答案

>>> from itertools import combinations
>>> nums = [[0,25], [1,54], [2,76], [3,13], [4,79]]
>>> list(combinations(nums, r=2))
[([0, 25], [1, 54]), ([0, 25], [2, 76]), ([0, 25], [3, 13]), ([0, 25], [4, 79]), ([1, 54], [2, 76]), ([1, 54], [3, 13]), ([1, 54], [4, 79]), ([2, 76], [3, 13]), ([2, 76], [4, 79]), ([3, 13], [4, 79])]

顾名思义,itertools.combinations 返回一个迭代器(延迟生成组合),您必须使用 list(...) 构造函数来获取迭代器你的 list 。不过,通常迭代器更可取,因为您可能只需要迭代组合。

for a, b in combinations(nums, r=2):
pass

如果不需要存储结果,就不要构造列表。

关于python - 基于一个键属性的python中嵌套列表的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17084543/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com