Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按索引将列表元素分组为元组_Python_List_Tuples - Fatal编程技术网

Python 按索引将列表元素分组为元组

Python 按索引将列表元素分组为元组,python,list,tuples,Python,List,Tuples,我有一个类似于[1,2,3,1,2,3,1,2,3]的列表,我想根据它们的索引对公共元素进行分组,因此结果是:[(0,3,6),(1,4,7),…]使用字典;最简单的方法是: from collections import defaultdict indices = defaultdict(list) for index, value in enumerate(inputlist): indices[value].append(index) result = [tuple(indic

我有一个类似于
[1,2,3,1,2,3,1,2,3]
的列表,我想根据它们的索引对公共元素进行分组,因此结果是:
[(0,3,6),(1,4,7),…]
使用字典;最简单的方法是:

from collections import defaultdict

indices = defaultdict(list)
for index, value in enumerate(inputlist):
    indices[value].append(index)

result = [tuple(indices[value]) for value in sorted(indices)]

这假设您希望索引按值排序顺序排序。

如果顺序很重要,则使用
集合。OrderedDict
否则使用
集合。defaultdict

>>> from collections import OrderedDict
>>> lis = [1,2,3,1,2,3,1,2,3]
>>> d = OrderedDict()
>>> for i, item in enumerate(lis):
    d.setdefault(item, []).append(i)
...     
>>> d.values()
[[0, 3, 6], [1, 4, 7], [2, 5, 8]]