簡體   English   中英

"如何將列表列表轉換為python中的對象列表?"

[英]How to convert list of list to list of objects in python?

我正在使用python 3.7。 我有一個數組數組:

[[1,2,3,4],[5,6,7,8],[9,10,11,12]]

如果我們閱讀json.dumps的文檔:

使用此轉換表將 obj 序列化為 JSON 格式的 str 。

這不是我們想要的。 我們希望將您的列表列表轉換為字典列表,其中鍵['name', 'surname', 'price', 'location']與每個子列表一起壓縮。

一個簡單的解決方案是在列表理解中使用zip()

lst =  [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 

keys = ['name', 'surname', 'price', 'location']

print([dict(zip(keys, sublst)) for sublst in lst])

輸出:

[{'name': 1, 'surname': 2, 'price': 3, 'location': 4}, {'name': 5, 'surname': 6, 'price': 7, 'location': 8}, {'name': 9, 'surname': 10, 'price': 11, 'location': 12}]

注意:這假設壓縮列表的長度相等。 否則我們可以使用itertools.zip_longest來壓縮不均勻長度的列表。

輸入<\/strong>

a = ["AB", "corona"]
b = ["india",'openVINO']
c = ["korea"]
d = ["26", "10.mp3", "Nvidia.mp4"]
e = ["washington DC",6]
f = ['swiss']

import itertools

lst = [a,b,c,d,e,f]
# print(lst)
lsts = list(itertools.product(*lst))
for lst in lsts:
  print('\n')
  for con in lst:
    print(con)

從您作為示例給出的輸出來看,我猜您正在尋找創建一個字典列表 以下腳本應授予您保存為 new_list 的輸出

array=[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
new_list = []
for element in array:
    temp_dict = {}
    for x in element:
        if element.index(x) == 0:
            temp_str = 'name'
        elif element.index(x) == 1:
            temp_str = 'surname'
        elif element.index(x) == 2:
            temp_str = 'price'
        elif element.index(x) == 3:
            temp_str = 'location'
        temp_dict[temp_str] = x
    new_list.append(temp_dict)
print(new_list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM