简体   繁体   English

刚开始学习 python; 当我使用列表推导时,为什么这个 for 循环的打印不同? 我如何使循环相同?

[英]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?

from my understanding shouldn't the print for X be the same on both?根据我的理解,两者的 X 打印不应该相同吗? the answer i need is the one that comes from the list-comprehension, which is a new list where every element is -1 from the original list.我需要的答案是来自列表理解的答案,这是一个新列表,其中每个元素都是原始列表中的 -1。 But the for-loop one only gives 1 element, I also don't know how that element is calculated.但是 for 循环只给出 1 个元素,我也不知道该元素是如何计算的。 Printing x just gives the last element of the list.打印 x 只给出列表的最后一个元素。 I'm sure i'm doing something wrong but i'm not sure how to get a list from just using the for-loop.我确定我做错了什么,但我不确定如何仅使用 for 循环来获取列表。 WHAT IS CONFUSING ME is that if the print(x) is part of the for loop it will print the elements of the desired list I need, but NOT in a list, which means the math I wrote works as intended, right?令我困惑的是,如果 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)

First thing, list is a protected keyword.首先,list 是受保护的关键字。 You should be using list_ at least (that's the naming convention if you really need to use list as the name).您至少应该使用 list_ (如果您确实需要使用 list 作为名称,那就是命名约定)。

The second iterates element by element, and prints each of the elements, what you want is in the loop to set each of the elements one by one, and then print x (not inside the loop).第二个逐个元素迭代,并打印每个元素,你想要的是在循环中一个一个地设置每个元素,然后打印 x (不在循环内)。

list_= [1,2,3,4,5]

x=[]
for i in list_:
  x.append(i-1)
print(x)

You should append like this:你应该像这样 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.

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