一行程序: 使用索引作为键从 list 创建字典

我想从给定的列表 只有一句话中创建一个字典。字典的键是索引,值是列表的元素。就像这样:

a = [51,27,13,56]         #given list


d = one-line-statement    #one line statement to create dictionary


print(d)

产出:

{0:51, 1:27, 2:13, 3:56}

我没有任何具体的要求,为什么我要 线。我只是在探索巨蟒,想知道这是否可行。

120262 次浏览
a = [51,27,13,56]
b = dict(enumerate(a))
print(b)

will produce

{0: 51, 1: 27, 2: 13, 3: 56}

enumerate(sequence, start=0)

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

Try enumerate: it will return a list (or iterator) of tuples (i, a[i]), from which you can build a dict:

a = [51,27,13,56]
b = dict(enumerate(a))
print b

With another constructor, you have

a = [51,27,13,56]         #given list
d={i:x for i,x in enumerate(a)}
print(d)
{x:a[x] for x in range(len(a))}

Simply use list comprehension.

a = [51,27,13,56]
b = dict( [ (i,a[i]) for i in range(len(a)) ] )
print b