Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

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? 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. But the for-loop one only gives 1 element, I also don't know how that element is calculated. Printing x just gives the last element of the list. I'm sure i'm doing something wrong but i'm not sure how to get a list from just using the for-loop. 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?

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First thing, list is a protected keyword. You should be using list_ at least (that's the naming convention if you really need to use list as the name).

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).

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...