【问题标题】:Combinations in of nested lists in python based on a one key attribute基于一键属性的python中嵌套列表的组合
【发布时间】:2013-06-13 10:16:20
【问题描述】:

我不知道该怎么形容。我将展示一个示例: 这是我的输入列表

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

这是我想要的输出:

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

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

我试过这样的迭代工具:

perm_list = itertools.combinations(task_list, 10)

但它所做的只是显示:

itertools.combinations object at 0x0120B060

【问题讨论】:

  • itertools 调用返回迭代器;要获取列表,请致电list()perm_list = list(perm_list)
  • 我不明白你的输出

标签: python list nested combinations


【解决方案1】:
>>> 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(...) 构造函数的迭代器来获取您的列表。但通常迭代器更可取,因为您可能只需要迭代组合。

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

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

【讨论】:

  • 为什么使用 r=2?我不能只给 2 个吗?
  • 任何人都可以指点我生成给定数组的 k 大小子集的算法吗?网上看了很多代码,看不懂:(
  • @user2138665 当然不用r=也可以,自己试试吧! “指出用于生成给定数组的 k 大小子集的算法”是这个 (docs.python.org/2/library/itertools.html#itertools.combinations) 你的意思
  • 我确实在没有 r 的情况下尝试过它,它成功了:) 只是想知道 r 是干什么用的
  • @Frkdiablo 在数学符号中似乎是k,不知道为什么它被称为r
猜你喜欢
  • 1970-01-01
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多