简体   繁体   English

在 python 中的列表中使用 for 循环

[英]Using for loop inside list in python

I am confused between these 2 implementations:我对这两种实现感到困惑:

Implementation 1:实施1:

arr1 = []
arr2 = []
for j in range(2):
    arr1.append({"vals":[random() for j in range(2)]} )
arr2.append(arr1)

for i in arr2:
   print(i)

Implementation 2:实施2:

arr3 = [{'vals': [random() for i in range(2)]} for i in range(2)]

for i in arr3:
   print(i)

Outputs:输出:

Implementation1:实施1:

[{'vals': [0.36439704360819525, 0.8234398731777764]}, {'vals': [0.8452416981328936, 0.42974230274939684]}] [{'vals': [0.36439704360819525, 0.8234398731777764]}, {'vals': [0.8452416981328936, 0.42974230274939684]}]

Implementation2:实施2:

{'vals': [0.2974249134210081, 0.515705525022607]} {'vals': [0.8142081726400429, 0.6701375952682302]} {'vals': [0.2974249134210081, 0.515705525022607]} {'vals': [0.8142081726400429, 0.6701375952682302]}

Is there a difference between the 2 implementation of for loop and can I do the second implementation with a external for loop? for循环的2个实现之间有区别吗,我可以用外部for循环做第二个实现吗?

In your implementation1, you create arr1 as an array with 2 items like {vals:[]}, and append to arr2 which is an array with one item that is arr1在您的实现1中,您将 arr1 创建为一个包含 2 个项目的数组,例如 {vals:[]},以及 append 到 arr2,这是一个包含 arr1 项目的数组

in implementation2, arr3 is created like arr1 in implementation1.在 implementation2 中,arr3 的创建方式与 implementation1 中的 arr1 类似。 But there isn't any arr2 - I guess you have a typo here, you tend to print i in arr3, which are like {vals:[]}.但是没有任何 arr2 - 我猜你这里有错字,你倾向于在 arr3 中打印 i,就像 {vals:[]}。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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