当前位置: 动力学知识库 > 问答 > 编程问答 >

python - How to return items of for loop into a single list?

问题描述:

I do not know how I can get all the items from a for loop with a range in a list instead of getting them all separate.

Lets say I have this code

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

new = []

for item in list1[0:-1]:

new = item+1

print(new)

so if I run this I would get

2

3

4

5

but I need to get this:

[2,3,4,5]

the whole point of this problem is to add 1 to every number of the original list except the last one and then replace the third number with a 0. But if the numbers I get back are not in a list I do not know how to call the third item which I would get like this:

new[2]=0

网友答案:

You could use list.append():

list1 = [1,2,3,4,5]
list2 = []
for item in list1[0:-1]:
    list2.append(item + 1)

Alternatively, you could use a list comprehension:

list2 = [item + 1 for item in list1[0:-1]]
网友答案:

Here's a one-liner to replace every item x in a list with x + 1, except the third one, which will be replaced by 0. Also, I'll pass list1[:-1] to the list comprehension to omit the last element, as OP already did:

list1 = [1,2,3,4,5]
new = [x + 1 if i != 2 else 0 for i,x in enumerate(list1[:-1])]
# new == [2, 3, 0, 5]
网友答案:

This should work

list1=[1,2,3,4,5]
print [x+1 if i != 2 else 0 for i, x in enumerate(list1)]
#[2,3,0,5,6]
分享给朋友:
您可能感兴趣的文章:
随机阅读: