gpt4 book ai didi

python - 一个类轮 : creating a dictionary from list with indices as keys

转载 作者:IT老高 更新时间:2023-10-28 21:12:02 25 4
gpt4 key购买 nike

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

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}

我对为什么要 one 行没有任何具体要求。我只是在探索python,想知道这是否可能。

最佳答案

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

会产生

{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:

关于python - 一个类轮 : creating a dictionary from list with indices as keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16607704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com