一个班轮:从列表创建一个字典,索引为键 [英] One liner: creating a dictionary from list with indices as keys

查看:268
本文介绍了一个班轮:从列表创建一个字典,索引为键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个给定的列表中创建一个字典,只需一行。字典的键将是索引,值将是列表的元素。这样的一个例子:

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)

输出:

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

我没有任何具体要求,为什么我想要一个行。我只是在探索python,并想知道是否可行。

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)

将产生

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




enumerate(sequence,start = 0)

返回枚举对象。 序列必须是序列,迭代器或支持迭代的其他对象。由 enumerate()返回的迭代器的 next()方法返回一个元组包含一个计数(从起始,默认为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:

这篇关于一个班轮:从列表创建一个字典,索引为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆