Python 中的迭代器展平元组

Flatten tuple from iterator in Python

我有一个项目,我必须遍历列表中的每一对,还要访问每个项目的索引。我找到了this thread,这里建议使用itertools.combinations + enumerate,eg:

>>> mylist = ["a", "b", "c"]
>>> for x, y in itertools.combinations(enumerate(mylist), 2):
...     print(f"x: {x}, y: {y}")

x: (0, 'a'), y: (1, 'b')
x: (0, 'a'), y: (2, 'c')
x: (1, 'b'), y: (2, 'c')

我想解压这些以便我可以单独使用索引和项目,例如:

>>> for x, y in itertools.combinations(enumerate(mylist), 2):
...     index_x, item_x = x
...     index_y, item_y = y
...     print(f"index_x: {index_x}, item_x: {item_x}, index_y: {index_y}, item_y: {item_y}")

index_x: 0, item_x: a, index_y: 1, item_y: b
index_x: 0, item_x: a, index_y: 2, item_y: c
index_x: 1, item_x: b, index_y: 2, item_y: c

但是有没有办法在循环头中解压这些内容?以下:

>>> for index_x, item_x, index_y, item_y in itertools.combinations(enumerate(mylist), 2):
...     print(f"index_x: {index_x}, item_x: {item_x}, index_y: {index_y}, item_y: {item_y}")

结果:ValueError:没有足够的值来解压(预期 4,得到 2)

你可以这样做:

>>> for (index_x, item_x), (index_y, item_y) in itertools.combinations(enumerate(mylist), 2):
...     print(f"index_x: {index_x}, item_x: {item_x}, index_y: {index_y}, item_y: {item_y}")
    
index_x: 0, item_x: a, index_y: 1, item_y: b
index_x: 0, item_x: a, index_y: 2, item_y: c
index_x: 1, item_x: b, index_y: 2, item_y: c