[英]Python, How to efficiently make a nested dictionary from a list of lists
[英]how to make a nested list with three types of lists in python?
我有三個清單:
EX_Num = [1.0, 2.0, 3.0]
Height_str = ['tall', 'medium', 'short']
total_carbon = [8.425169446611104, 8.917085904771866, 6.174348482965436]
如何制作一個嵌套列表,其中column1 = EX_Num
, column2 = Height_str
和column3 = total_carbon
?
不清楚你在問什么......但如果你只想要一個列表列表,只需附加它們。
>>> nested_list.append(EX_Num)
>>> nested_list.append(Height_str)
>>> nested_list.append(total_carbon)
>>> nested_list
[[1.0, 2.0, 3.0], ['tall', 'medium', 'short'], [8.425169446611104, 8.917085904771866, 6.174348482965436]]
如果您希望將所有值放入一個列表中,只需將它們連接起來即可。
>>> nested_list = EX_Num + Height_str + total_carbon
>>> nested_list
[1.0, 2.0, 3.0, 'tall', 'medium', 'short', 8.425169446611104, 8.917085904771866, 6.174348482965436]
如果你需要不同的東西,你需要讓你的問題更清楚。]
根據評論編輯:
如果您知道所有列表的長度相同:
nested_list = []
# be careful, if the lists aren't all the same length, you will get errors
for x in range(len(EX_Num)):
tmp = [EX_Num[x], Height_str[x], total_carbon[x]]
nested_list.append(tmp)
您可以使用內置的zip
函數將多個可迭代對象連接到元組中:
ex = [1.0, 2.0, 3.0]
height = ['tall', 'medium', 'short']
total_carbon = [8.4, 8.9, 6.1]
joint = zip(ex, height, total_carbon)
print(joint)
# [(1.0, 'tall', 8.4), (2.0, 'medium', 8.9), (3.0, 'short', 6.1)]
注:請不要使用“匈牙利命名法”為您的變量名( _num
, _str
等) -他們只是混亂,特別是在像Python這樣的動態語言。
如果您需要將相關數據組合在一起,為它創建一個簡單的容器類型更具可讀性。 namedtuple
非常適合這個:
from collections import namedtuple
Thing = namedtuple('Thing', ['ex', 'height', 'total_carbon'])
my_things = [Thing(*t) for t in zip(ex, height, total_carbon)]
現在您可以按名稱引用東西——例如, my_things[0].height
而無需記住每個屬性的索引位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.