0

从字符串/列表创建字典的最有效方法是什么?例如,如果我有一个 list ['a', 'b', 'c', 'd'],我将如何创建以列表元素为键、索引为值的字典?上面的列表看起来如何:{'a': 0, 'b': 1, 'c': 2, 'd': 3}

4

2 回答 2

5

enumerate()将返回元素及其索引,您可以在字典理解中使用它。

l = ['a', 'b', 'c', 'd']
d = {value: index for index, value in enumerate(l)}
于 2020-04-01T17:40:39.673 回答
0

你可以使用这个:

lista = ['a', 'b', 'c', 'd']
dictionary = {}

n = 0
for el in lista:
    dictionary[el] = n
    n += 1
于 2020-04-01T17:43:32.827 回答