【问题标题】:Python itertools.combinations: how to obtain the indices of the combined numbersPython itertools.combinations:如何获取组合数字的索引
【发布时间】:2015-01-24 21:20:57
【问题描述】:

Python 的 itertools.combinations() 创建的结果是数字的组合。例如:

a = [7, 5, 5, 4]
b = list(itertools.combinations(a, 2))

# b = [(7, 5), (7, 5), (7, 4), (5, 5), (5, 4), (5, 4)]

但我也想获得组合的索引,例如:

index = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

我该怎么做?

【问题讨论】:

  • itertools.combinations(range(len(a)), 2)?

标签: python itertools


【解决方案1】:

您可以使用 range 来获取 combinations 生成的索引的顺序。

>>> list(itertools.combinations(range(3), 2))
[(0, 1), (0, 2), (1, 2)]

所以你可以使用len(a):

>>> list(itertools.combinations(range(len(a)), 2))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

【讨论】:

  • 确保使用 itertools.combination 而不仅仅是组合
【解决方案2】:

你可以使用枚举:

>>> a = [7, 5, 5, 4]
>>> list(itertools.combinations(enumerate(a), 2))
[((0, 7), (1, 5)), ((0, 7), (2, 5)), ((0, 7), (3, 4)), ((1, 5), (2, 5)), ((1, 5), (3, 4)), ((2, 5), (3, 4))]
>>> b = list((i,j) for ((i,_),(j,_)) in itertools.combinations(enumerate(a), 2))
>>> b
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

【讨论】:

  • 智能组合!
  • 这很 Pythonic
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 1970-01-01
相关资源
最近更新 更多