设置包含1个列表和列表列表的字典

时间:2014-02-23 20:04:02

标签: 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.099999999999998, 12.157142857142858, 12.314285714285715, 14.428571428571429]]

我希望mydict看起来像这样:

{"monday":(16.0 ,10.0 , 12.857142857142858), "tuesday":(16.5, 9.2, 13.0) ...

所以我想要的是迭代列表days和2d阵列temperatures。可能有一个for循环,但我该如何设置呢?

4 个答案:

答案 0 :(得分:6)

使用词典理解:

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

答案 1 :(得分:2)

试试这个:

dict(zip(days,map(tuple, temperatures)))

首先制作所有温度数组元组,构建一个key-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)}

答案 2 :(得分:1)

将两个列表压缩在一起。你需要一个嵌套的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,))

答案 3 :(得分:1)

我相信,这是最短的方式:

dict(zip(days, zip(*temperatures)))

zip(*temperatures)会创建一个元组列表[(16.0, 10.0, 12.857142857142858), ...],然后另一个zip将这些元组与键配对,最后,dict接受(key, value)的序列夫妇。