[英]New to learning python; why is the print for this for-loop different when I use a list comprehension? how do i make the loop be the same?
根据我的理解,两者的 X 打印不应该相同吗? 我需要的答案是来自列表理解的答案,这是一个新列表,其中每个元素都是原始列表中的 -1。 但是 for 循环只给出 1 个元素,我也不知道该元素是如何计算的。 打印 x 只给出列表的最后一个元素。 我确定我做错了什么,但我不确定如何仅使用 for 循环来获取列表。 令我困惑的是,如果 print(x) 是 for 循环的一部分,它将打印我需要的所需列表的元素,但不在列表中,这意味着我编写的数学按预期工作,对吗?
list= [1,2,3,4,5]
#loop
x=[]
for i in list:
x=[i-1]
print(x)
#list comprehension
x=[i-1 for i in list]
print(x)
#confusing part where this print will be the same as the comprehension but not in a list form
x=[]
for i in list:
x=[i-1]
print(x)
首先,list 是受保护的关键字。 您至少应该使用 list_ (如果您确实需要使用 list 作为名称,那就是命名约定)。
第二个逐个元素迭代,并打印每个元素,你想要的是在循环中一个一个地设置每个元素,然后打印 x (不在循环内)。
list_= [1,2,3,4,5]
x=[]
for i in list_:
x.append(i-1)
print(x)
你应该像这样 append :
lst= [1,2,3,4,5]
#loop
x=[]
for i in lst:
x.append(i-1)
print(x)
#output: [0, 1, 2, 3, 4]
#list comprehension
x=[i-1 for i in lst]
print(x)
#output: [0, 1, 2, 3, 4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.