Python 设置包含1个列表和列表列表的词典
我有:Python 设置包含1个列表和列表列表的词典,python,list,python-3.x,dictionary,tuples,Python,List,Python 3.x,Dictionary,Tuples,我有: mydict = {} days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"] temperatures = [[16.0, 16.5, 17.2, 16.8, 18.8, 15.5, 21.4], [10.0, 9.2, 9.5, 10.0, 6.8, 9.4, 11.7], [12.857142857142858, 13.0, 13.442857142857145, 13.09
mydict = {}
days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
temperatures = [[16.0, 16.5, 17.2, 16.8, 18.8, 15.5, 21.4], [10.0, 9.2, 9.5, 10.0, 6.8, 9.4, 11.7], [12.857142857142858, 13.0, 13.442857142857145, 13.099999999999998, 12.157142857142858, 12.314285714285715, 14.428571428571429]]
我希望mydict的外观如下所示:
{"monday":(16.0 ,10.0 , 12.857142857142858), "tuesday":(16.5, 9.2, 13.0) ...
所以我想迭代列表
天
和2d数组温度
。可能使用for
循环,但如何设置它?使用dict理解:
>>> {k : list(v) for k, v in zip(days, zip(*temperatures))}
{'monday': [16.0, 10.0, 12.857142857142858],
'tuesday': [16.5, 9.2, 13.0],
'friday': [18.8, 6.8, 12.157142857142858],
'wednesday': [17.2, 9.5, 13.442857142857145],
'thursday': [16.8, 10.0, 13.099999999999998],
'sunday': [21.4, 11.7, 14.428571428571429],
'saturday': [15.5, 9.4, 12.314285714285715]}
如果您想要元组而不是列表,请使用
tuple(v)
。只需将两个列表压缩在一起即可。你需要一个嵌套的for循环来获取每天->温度
days = ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
temperatures = [[16.0, 16.5, 17.2, 16.8, 18.8, 15.5, 21.4], [10.0, 9.2, 9.5, 10.0, 6.8, 9.4, 11.7], [12.857142857142858, 13.0, 13.442857142857145, 13.099999999999998, 12.157142857142858, 12.314285714285715, 14.428571428571429]]
for day, temps in zip(days,temperatures):
for temp in temps:
print("On %s the temperature was %f" %(day,temp,))
试试这个:
dict(zip(days,map(tuple, temperatures)))
首先创建所有数组元组,构建关键val条目列表,并使用此列表构建字典,您将得到:
{'tuesday': (10.0, 9.2, 9.5, 10.0, 6.8, 9.4, 11.7), 'wednesday': (12.857142857142858, 13.0, 13.442857142857145, 13.099999999999998, 12.157142857142858, 12.314285714285715, 14.428571428571429), 'monday': (16.0, 16.5, 17.2, 16.8, 18.8, 15.5, 21.4)}
我相信这是最短的途径:
dict(zip(days, zip(*temperatures)))
zip(*temperatures)
将创建一个元组列表[(16.0,10.0,12.857142857142858),…]
,然后另一个zip
将这些元组与键配对,最后,dict
接受一系列(键,值)
对。您可以用元组替换lambda x:tuple(x)
。