Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何通过调整字典来创建列表?_Python_Python 3.x_List_Dictionary - Fatal编程技术网

Python 如何通过调整字典来创建列表?

Python 如何通过调整字典来创建列表?,python,python-3.x,list,dictionary,Python,Python 3.x,List,Dictionary,有这样的字典吗 d = { 'airplane': 0, 'automobile': 1, 'bird': 2, 'cat': 3, 'deer': 4, 'dog': 5, 'frog': 6, 'horse': 7, 'ship': 8, 'truck': 9 } 和一份清单 l = [3, 4, 1, 7, 9,

有这样的字典吗

d = {
        'airplane': 0, 
        'automobile': 1, 
        'bird': 2, 
        'cat': 3, 
        'deer': 4, 
        'dog': 5, 
        'frog': 6, 
        'horse': 7, 
        'ship': 8, 
        'truck': 9
}
和一份清单

l = [3, 4, 1, 7, 9, 0]
如何创建字典的新列表

new_list = ['cat', 'deer', 'automobile', 'horse', 'truck', 'airplane']
这个怎么样

d={'player':0,'automobile':1,'bird':2,'cat':3,'deer':4,'dog':5,'frog':6,'horse':7,'ship':8,'truck':9}
l=[3,4,1,7,9,0]
反转的_d={v:k代表k,v代表d.items()}
新列表=[对于l中的i,反向的d[i]
打印(新列表)
#[‘猫’、‘鹿’、‘汽车’、‘马’、‘卡车’、‘飞机’]

请注意,一般来说,生成
reversed\u d
不会很好地处理重复项。

首先,示例中的字典
d
不是理想的查找结构,因为字典是用键而不是值索引的。此外,不能保证值在所有键上都是唯一的

如果确定这些值是唯一的,则可以更改字典:

d = {'airplane': 0, 'automobile': 1, 'bird': 2, 'cat': 3, 'deer': 4, 'dog': 5, 'frog': 6, 'horse': 7, 'ship': 8, 'truck': 9}
di = {value: key for key, value in d.items()}
之后,获取第二个列表只是另一个列表理解:

l = [3, 4, 1, 7, 9, 0]
new_list = [di[key] for key in l]

只需按如下方式进行尝试:

d = {'airplane': 0, 'automobile': 1, 'bird': 2, 'cat': 3, 'deer': 4, 'dog': 5, 'frog': 6, 'horse': 7, 'ship': 8, 'truck': 9}
l = [3, 4, 1, 7, 9, 0]

new_list = [list(d)[i] for i in l]

您只需要从字典“d”中获取键,其值与列表“l”中存在的数字对应。通过使用列表理解,您可以轻松做到这一点

print([list(d.keys())[list(d.values()).index(num)] for num in l])
由于您使用的是python-3,因此d.keys()和d.values()不会返回列表;因此,您需要自己执行此操作,因此它们是使用list()进行类型转换的

输出

['cat', 'deer', 'automobile', 'horse', 'truck', 'airplane']

我不确定那应该是一本字典;两个键可以具有相同的值。但基本上:迭代l,在字典中搜索具有该值的(第一个?)键,将该键放入一个新的列表中。从dict
d={'framework':0,'automobile':0,'bird':0}
?新列表的可能重复项应该表示该键对应的值。所以,如果我有2,新列表必须给出'automobile'@ClaWnN,你知道dict键是无序的吗?所以为什么一定要给"汽车"??
['cat', 'deer', 'automobile', 'horse', 'truck', 'airplane']