如何将list1转换为list2?
list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = [[{1:2},{11:22}],[{3:4},{33:44}]]
列表2的键是list1的奇数元素,而list2的值是list1的偶数
我尝试过如下,但获得不同的list3。
def f(list1):
newlist=[]
for i in range(0, len(list1), 2):
dict1={}
for j,key in enumerate (list1[i]):
dict1[key]=list1[i+1][j]
newlist.append(dict1)
print newlist
f(list1)
[{1: 2, 11: 22}, {1: 2, 11: 22}, {33: 44, 3: 4}, {33: 44, 3: 4}]
答案 0 :(得分:2)
作为列表理解:
list1 = [[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = [[{tup[0]: tup[1]} for tup in zip(*list1[i:i+2])] for i in range(0, len(list1), 2)]
# Prints as [[{1: 2}, {11: 22}], [{3: 4}, {33: 44}]]
编辑:这个更干净一些(也许更像pythonic)。
list2 = [[dict([tup]) for tup in zip(*sublist)] for sublist in zip(list1[0::2], list1[1::2])]
Edit2:列表推导等同于这个嵌套的for循环。
list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
list2 = list()
# Iterate over list1 two by two, first round: sublist = ([1,11], [2,22])
for sublist in zip(list1[0::2], list1[1::2]):
inner_result = list()
# Second loop equivalent to for tup in zip(sublist[0], sublist[1])
for tup in zip(*sublist): # First round, tup will be (1,2) then (11, 22)
# Make dictionary from tuple, for first tuple this is
# equivalent to: dict([(1,2)]) == {1: 2}
new_dict = dict([tup])
inner_result.append(new_dict)
list2.append(inner_result)
答案 1 :(得分:1)
您的代码几乎是正确的。问题出在这里:
dict1={}
for j,key in enumerate (list1[i]):
dict1[key]=list1[i+1][j]
newlist.append(dict1)
在循环中你使用相同的词典。所以要实现你想要的只是将dict1
定义移动到循环中(在每次迭代时创建一个新的dict):
for j,key in enumerate (list1[i]):
dict1={}
dict1[key]=list1[i+1][j]
newlist.append(dict1)
答案 2 :(得分:1)
这就是你要找的东西:
list2 = []
ind = 0
while ind < len(list1):
d1 = {list1[ind][0]: list1[ind+1][0]}
d2 = {list1[ind][1]: list1[ind+1][1]}
list2.append([d1, d2])
ind += 2
print list2 # prints [[{1: 2}, {11: 22}], [{3: 4}, {33: 44}]]
答案 3 :(得分:1)
创建列表 - &gt;列表 - &GT;从给定列表中的词典,考虑第0项是列表1中的键,第1项是值。
list1
中的每个项目,因为我们需要list1
中每个项目的索引。list1
result
列表。演示:
>>> list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
>>> for i, value in enumerate(list1):
... if i%2==0:
... try:
... result.append([{value[0]:list1[i+1][0]}, {value[1]:list1[i+1][1]}])
... except IndexError:
... print "Index Over"
... break
...
>>> result
[[{1: 2}, {11: 22}], [{3: 4}, {33: 44}]]
答案 4 :(得分:1)
这是你在找什么?
def f(lista):
lnew = []
i=0
while i < len(lista):
dict1 = {lista[i][0]:lista[i+1][0]}
dict2 = {lista[i][1]:lista[i+1][1]}
lnew.append([dict1,dict2])
i += 2
return lnew
lold = [[1, 11], [2, 22], [3, 33], [4, 44]]
print(f(lold))
答案 5 :(得分:1)
In [27]: list1 =[[1, 11], [2, 22], [3, 33], [4, 44]]
In [28]: l2 = [ zip(item, list1[k+1]) for k,item in enumerate(list1) if k +1 < len(list1) and k % 2 == 0 ]
In [29]: [[{ item[0][0]: item[1][0]}, [{item[0][1]: item[1][1] }] ] for item in l2]
Out[29]: [[{1: 11}, [{2: 22}]], [{3: 33}, [{4: 44}]]]
答案 6 :(得分:0)
newlist=[]
for i in range(0, len(list1), 2):
dict1={}
for j,key in enumerate (list1[i]):
dict1[key]=list1[i+1][j]
newlist.append([dict1])
print newlist
更新我的编码,从2nd下的newlist.append(dict1)到1st下的newnlist.append([dict1])