python - 如何将多个列表转换为python中的字典列表?

标签 python

我有一个程序,它接受 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

这是我的输出:
[2, 3, 4, 5]
[2, 2, 13, 15]
[1, 2, 6, 6]
[1, 0, 7, 9]
[False, False, False, False]

这是我的问题:
1)我想将结果映射到每个地方的字典列表,如下所示:
[{'initial_num': '5', 'after_borrow': '15', 'state': True, 'after_subtract': '9'},
{'initial_num': '4', 'after_borrow': '13', 'state': True, 'after_subtract': '7'}...]

我该如何做到这一点,以便我在列表中有 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)]

关于python - 如何将多个列表转换为python中的字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60390596/

相关文章:

python - Python 中的 MySQL INSERT 语句

python - 为什么隐蔽的 Tensorflow 升级到 2.9.1 会破坏使用 GPU 而不是 CPU 的 Google Colab Jupyter 笔记本?

python - 是否需要范围(len(a))?

python - 比较 csv 文件中的两行 - Python

php - Python 库和驱动程序

python - 使用外键在 Django 中抽象基类继承

Python/Flask 表单错误 - AttributeError : 'unicode' object has no attribute '__call__'

python - 如何在以本地模式运行的 pyspark 中从 S3 读取数据?

python - Python 通用加密哈希库中的 Whirlpool

python - 尝试每小时向 channel 发送消息