[英]How to convert several lists to a list of dicts in python?
I have a program that takes 2 numbers and subtracts them and also tells us if the individual places ie ones, tens and hundreds are smaller than the number they are being subtracted from and if they need to borrow.我有一个程序,它接受 2 个数字并将它们相减,并告诉我们单个位置(即一个、十个和数百个)是否小于它们被减去的数字,以及它们是否需要借用。
a=2345
b=1266
o=[int(d) for d in str(a)]
a=[int(d) for d in str(a)]
b=[int(d) for d in str(b)]
x=len(a)
y=len(b)
i=1
state=[]
c=[]
for n in range(x):
if a[x-i]<b[y-i]:
a[x-i]+=10
a[x-i-1]-=1
state.append(True)
else:
state.append(False)
i+=1
i=1
for m in range(x):
c.append(a[x-i]-b[y-i])
i+=1
c=c[::-1]
print(o) #before borrow
print(a) #after borrow
print(b) #number to subtract
print(c) #result
print(state) #if borrowed
And this is my output:这是我的输出:
[2, 3, 4, 5]
[2, 2, 13, 15]
[1, 2, 6, 6]
[1, 0, 7, 9]
[False, False, False, False]
Here is my question: 1) I want to map the results to a list of dictionary for each place like below:这是我的问题:1)我想将结果映射到每个地方的字典列表,如下所示:
[{'initial_num': '5', 'after_borrow': '15', 'state': True, 'after_subtract': '9'},
{'initial_num': '4', 'after_borrow': '13', 'state': True, 'after_subtract': '7'}...]
How do I do this so that I have 4 dicts in the list each corresponding to a particular position?我该如何做到这一点,以便我在列表中有 4 个字典,每个字典对应于一个特定的位置?
您可以使用列表理解将您感兴趣的列表zip
到dict
s
l = [{'initial_num': x, 'after_borrow': y, 'state': z, 'after_subtract': k} for x, y, z, k in zip(o, a, state, c)]
This can achieve what you want.这可以实现你想要的。
a=2345
b=1266
o=[int(d) for d in str(a)]
a=[int(d) for d in str(a)]
b=[int(d) for d in str(b)]
x = len(a)
y = len(b)
i=1
state=[]
c=[]
for n in range(x):
if a[x-i] < b[y-i]:
a[x-i] += 10
a[x-i-1] -= 1
state.append(True)
else:
state.append(False)
i+=1
i=1
for m in range(x):
c.append(a[x-i]-b[y-i])
i += 1
c=c[::-1]
print(o) #before borrow
print(a) #after borrow
print(b) #number to subtract
print(c) #result
print(state) #if borrowed
result = []
for i in range(len(o)):
idx = len(o) - i - 1
result.append({
'initial_num': o[idx],
'after_borrow': a[idx],
'state': state[idx],
'after_subtract': c[idx]
})
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.