简体   繁体   中英

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.

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:

[{'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?

您可以使用列表理解将您感兴趣的列表zipdict 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM