Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_Dictionary - Fatal编程技术网

Python:从列表构建字典

Python:从列表构建字典,python,list,dictionary,Python,List,Dictionary,对于作业,我必须建立一个字典,其中键是列表中的元素,值是一个列表,其中包含每个元素的位置,例如: x = [13, 15, 27, 11, 13, 27] > dict = {13:[0,4], 15:[1], 27:[2,5], 11:[3]} 我无法从列表中的重复元素中获取位置 将此答案视为一个提示: x = [13, 15, 27, 11, 13, 27] for index, element in enumerate(x): print index, element &

对于作业,我必须建立一个字典,其中键是列表中的元素,值是一个列表,其中包含每个元素的位置,例如:

x = [13, 15, 27, 11, 13, 27]

> dict = {13:[0,4], 15:[1], 27:[2,5], 11:[3]}

我无法从列表中的重复元素中获取位置

将此答案视为一个提示:

x = [13, 15, 27, 11, 13, 27]
for index, element in enumerate(x):
    print index, element
>>> 0, 13
    1, 15
    2, 27
    3, 11
    4, 13
    5, 27

使用默认值为空的list和enumerate来提供索引

我想您必须使用循环或其他东西来代替(很可能)
index()
。试一试。如果一个数字在列表中出现两次以上怎么办?
from collections import defaultdict
d = defaultdict(list)
for i,j in enumerate(x):
    d[j].append(i)