如果你有很多變數,你不想硬編碼你的字典理解,這是一種方法。
注意:你需要有聲明的所有變量。
此外您還需要聲明變量名稱列表。
list_of_var_names = ['triangles', 'circles', 'squares']
dict(zip(index, [dict(zip(list_of_var_names, i))
for i in (globals().get(i) for i in list_of_var_names)]))
而且分分步:
In [1]: index = [1,2,3]
...:
...: triangles = [4,5,6]
...: circles = [7,8,9]
...: squares = [10,11,12]
...:
In [2]: list_of_var_names = ['triangles', 'circles', 'squares']
In [3]: [globals().get(i) for i in list_of_var_names] # getting list of variable values in list_of_var_names order
Out[3]: [[4, 5, 6], [7, 8, 9], [10, 11, 12]]
In [4]: [dict(zip(list_of_var_names, i)) for i in (globals().get(i) for i in lis
...: t_of_var_names)]
Out[4]:
[{'circles': 5, 'squares': 6, 'triangles': 4},
{'circles': 8, 'squares': 9, 'triangles': 7},
{'circles': 11, 'squares': 12, 'triangles': 10}]
In [5]: dict(zip(index, [dict(zip(list_of_var_names, i))
...: for i in (globals().get(i) for i in list_of_var_names)]
...:))
...:
Out[5]:
{1: {'circles': 5, 'squares': 6, 'triangles': 4},
2: {'circles': 8, 'squares': 9, 'triangles': 7},
3: {'circles': 11, 'squares': 12, 'triangles': 10}}
我想提一個更多的時間,這個解決方案,如果好,如果你得到一噸的變量,你不想顯式聲明字典理解。在其他情況下,使用此處介紹的其他解決方案會更合適,更具可讀性。
告訴我們您到目前爲止試過嗎? –