一个班轮:从列表中创建一个以索引为键的字典 [英] One liner: creating a dictionary from list with indices as keys
问题描述
我想从给定的列表中创建一个字典,在一行中.字典的键是索引,值是列表的元素.像这样:
a = [51,27,13,56] #给定的列表d = one-line-statement #创建字典的一行语句打印(四)
输出:
{0:51, 1:27, 2:13, 3:56}
我对为什么要一个线路没有任何具体要求.我只是在探索 python,想知道这是否可能.
a = [51,27,13,56]b = dict(enumerate(a))打印(b)
会产生
{0: 51, 1: 27, 2: 13, 3: 56}
<块引用>
返回一个枚举对象.sequence 必须是一个序列、一个迭代器或其他一些支持迭代的对象.enumerate()
返回的迭代器的 next()
方法返回一个 tuple
包含一个计数(从 start默认为 0) 和通过迭代序列获得的值:
I want to create a dictionary out of a given list, in just one line. The keys of the dictionary will be indices, and values will be the elements of the list. Something like this:
a = [51,27,13,56] #given list
d = one-line-statement #one line statement to create dictionary
print(d)
Output:
{0:51, 1:27, 2:13, 3:56}
I don't have any specific requirements as to why I want one line. I'm just exploring python, and wondering if that is possible.
a = [51,27,13,56]
b = dict(enumerate(a))
print(b)
will produce
{0: 51, 1: 27, 2: 13, 3: 56}
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 byenumerate()
returns atuple
containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:
这篇关于一个班轮:从列表中创建一个以索引为键的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!