当子列表仍然是大列表中的项目时,将子列表加入python中的列表中

时间:2017-04-14 17:20:26

标签: python list join

我有一个这样的清单:

l = ['1:4', '3:6', '5:4']

我想加入内部列表":"。我想把结果作为:

 var  data =[
    {header_id:"TR100001" detail_id:"2" item_code:"SPH001" price:"4000" weight:"2"},
    {header_id:"TR100001" detail_id:"3" item_code:"SPH002" price:"4500" weight:"2"},
    {header_id:"TR100001" detail_id:"4" item_code:"SPH003" price:"30000"weight:"2"},
    {header_id:"TR100001" detail_id:"5" item_code:"SPH004" price:"45000"weight:"2"}];

如何使用Python实现它?

3 个答案:

答案 0 :(得分:0)

您可以使用列表理解来实现此目的:

[':'.join(map(str, x)) for x in l]

答案 1 :(得分:0)

l = [[1,4], [3,6], [5,4]]
fl = []
for x in l:
    fl.append(str(x[0])+':'+str(x[1]))
print(fl) # Final List, also you can do: l = fl

但是,我认为你想做字典,如果这是真的,你必须这样做:

l = [[1,4], [3,6], [5,4]]
fd = {}
for x in l:
    fd[x[0]] = x[1]
print(fd) # Final Dictionary

<强>说明

l = [[1,4], [3,6], [5,4]]              # Your list
fl = []                                # New list (here will be the result)
for x in l:                            # For each item in the list l:
    fl.append(str(x[0])+':'+str(x[1])) # Append the first part [0] of this item with ':' and the second part [1].
print(fl)

使用词典:

l = [[1,4], [3,6], [5,4]]     # Your list
fd = {}                       # New dictionary
for x in l:                   # For each item in the list l:
    fd[x[0]] = x[1]           # Make a key called with the first part of the item and a value with the second part.
print(fd) # Final Dictionary

您还可以更轻松地制作字典:

l = [[1,4], [3,6], [5,4]] 
l = dict(l)                   # Make a dictionary with every sublist of the list (it also works with tuples), the first part of the sublist is the key, and the second the value.

答案 2 :(得分:-2)

你可以这样做:

final_list = []
for i in l:
    a = str(i[0])+':'+str(i[1])
    final_list.append(a)
print(final_list)