【问题标题】:Python itertools.combinations: how to obtain the indices of the combined numbers within the combinations at the same timePython itertools.combinations:如何同时获取组合内组合数的索引
【发布时间】:2020-12-29 15:09:15
【问题描述】:

根据此处提出的问题:Python itertools.combinations: how to obtain the indices of the combined numbers,给出以下代码:

import itertools
my_list = [7, 5, 5, 4]

pairs = list(itertools.combinations(my_list , 2))
#pairs = [(7, 5), (7, 5), (7, 4), (5, 5), (5, 4), (5, 4)]

indexes = list(itertools.combinations(enumerate(my_list ), 2)
#indexes = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]

有什么方法可以在一行中获取pairsindexes,这样我的代码就可以降低复杂度(例如,使用enumerate 或类似的东西)?

【问题讨论】:

  • 只需zip 两个迭代器,而不是将它们消耗到列表中。
  • 你能帮我怎么做吗?
  • 谢谢。我正在阅读以尽快获得解决方案。
  • 我不认为你的第二个例子的输出是正确的,如果你从枚举中获取元组的组合,这将是值 它们的索引,发出的第一项将是((0, 7), (1, 5))。您显示的将是仅索引组合的输出,例如来自range(len(my_list))

标签: arrays python-3.x list combinations itertools


【解决方案1】:

@Maf - 试试这个,这是@jonsharpe 之前建议的,使用zip

from pprint import pprint
from itertools import combinations

 my_list = [7, 5, 5, 4]
>>> pprint(list(zip(combinations(enumerate(my_list),2), combinations(my_list,2))))
[(((0, 7), (1, 5)), (7, 5)),
 (((0, 7), (2, 5)), (7, 5)),
 (((0, 7), (3, 4)), (7, 4)),
 (((1, 5), (2, 5)), (5, 5)),
 (((1, 5), (3, 4)), (5, 4)),
 (((2, 5), (3, 4)), (5, 4))]

【讨论】:

  • 我们同时写作。这似乎是最好的解决方案。我会选择你的答案。感谢您的回答!
【解决方案2】:

(显式优于隐式。简单优于复杂。) 我会使用 list-comprehension 的灵活性:

list((x, (x[0][1], x[1][1])) for x in list(combinations(enumerate(my_list), 2)))

这可以使用opertor.itemgetter之类的方法进一步扩展。

此外,这个想法是只运行一次迭代器,因此该方法也可以潜在地应用于其他非确定性迭代器,例如来自random.choicesyield

【讨论】:

    猜你喜欢
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 2018-06-07
    相关资源
    最近更新 更多