Python itertools.combinations:如何同时获取组合内组合数的索引
Python itertools.combinations: how to obtain the indices of the combined numbers within the combinations at the same time
根据此处提出的问题: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)]
有什么方法可以在一行中获取 pairs
和 indexes
以便我的代码具有较低的复杂性(例如使用 enumerate
或类似的东西)?
@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))]
(显式优于隐式。简单优于复杂。)
我会使用 list-comprehension 因为它的灵活性:
list((x, (x[0][1], x[1][1])) for x in list(combinations(enumerate(my_list), 2)))
这可以使用 opertor.itemgetter
.
等进一步扩展
另外,这个想法是 运行 只使用一次迭代器,这样该方法也可以潜在地应用于其他非确定性迭代器,例如 yield
来自 random.choices
.
根据此处提出的问题: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)]
有什么方法可以在一行中获取 pairs
和 indexes
以便我的代码具有较低的复杂性(例如使用 enumerate
或类似的东西)?
@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))]
(显式优于隐式。简单优于复杂。) 我会使用 list-comprehension 因为它的灵活性:
list((x, (x[0][1], x[1][1])) for x in list(combinations(enumerate(my_list), 2)))
这可以使用 opertor.itemgetter
.
另外,这个想法是 运行 只使用一次迭代器,这样该方法也可以潜在地应用于其他非确定性迭代器,例如 yield
来自 random.choices
.