0
Follow
0
View

In python, the result of each run of the for loop is stored in the dictionary

admin 超级管理员
2023-02-28 10:06


The current code only saves the result of one loop, so the output dictionary contains only one set of key-value pairs whose keys are "values" and whose values are the result of the last loop.

If you want to save the results of each loop to a dictionary, you can use a list inside the loop to store the results of each loop, and then convert the list to a dictionary when the loop is over. For example:

results = []
for i in range(1, 7):
    c = c + 1
    item = {"值": c}
    results.append(item)
dict_result = {"结果": results}
print(dict_result)

hemyname 注册会员
2023-02-28 10:06

Because item and the statement that prints item are not inside the for loop, but outside the for loop, only the last value is printed and the corresponding code can be placed inside the for loop;

Then if you want to save the result of each run in the dictionary, you need a different key. If you use "value" and the current value of i as the key, you can use this as the key in the loop, and then use the value of c as the value, and keep adding key pairs to the dictionary; If you want to put all the results of the run in a list as its value, that is, you only need one key and then print the result, the following example uses the first method:

change it as follows:

c = 0
z={}
for i in range(1, 7):
    c = c + 1
   
    #item = {"值": c}
   # print(item)
    z["值"+str(i)]=c  # 以"值"+i的值作为每一项的键,c的值作为每一项的值
   # print(z)

# 打印结果
print(z)
    
 

img

About the Author

Question Info

Publish Time
2023-02-28 10:06
Update Time
2023-02-28 10:06

Related Question

发射文章标题Kotlin流

如何在ArchLinux上更新python到最新版本?

如何获得SDL2上使用SDL_RenderDrawPoint()绘制的特定像素的颜色?

点击搜索按钮后调用react-infinite-scroll-component

用python编写大学习计算机。

Send DMs to a specific role members in Discord

为什么我的python代码返回一个导入错误?

Python—每隔10分钟创建一个新的日志文件

端口转发设置nginx到自签名证书

Python:在CSV文件中打印多个元组