Need clarification with my for loop logic in Python

时间:2016-02-03 04:10:07

标签: python for-loop

The output should have been [2, 18, 6, 16, 10, 14].

my_list = [1, 9, 3, 8, 5, 7]

for number in my_list:
    number = 2 * number

print my_list     

The problem is that it prints the same my_list values. The logic number = 2 * number isn't even executed?

5 个答案:

答案 0 :(得分:3)

您没有更新列表,只是更新数字变量:

for number in my_list:
    number = 2 * number

有可能这样做:

使用枚举:

my_list = [1, 9, 3, 8, 5, 7]

for index,number in enumerate(my_list):
    my_list[index] = 2 * number

print my_list     

使用列表理解:

my_list = [2*x for x in my_list]

使用Lambda和map:

my_list = map(lambda x: 2*x, my_list)

答案 1 :(得分:1)

You can do this quickly in a list comprehension:

my_list = [1,9,3,8,5,7]
new_list = [2*x for x in my_list]

The problem with your code is that when you are looping through my_list, number is not the variable in the list; it is just the value of the that variable. Therefore, changing that value does not change the original variable.

答案 2 :(得分:0)

The way this is written will not modify the list in-place. You want something like a list comprehension that you can assign back into my_list.

my_list = [number * 2 for number in my_list]

答案 3 :(得分:0)

You have to assign the value back to the item in the list

my_list = [1,9,3,8,5,7]

for i, number in enumerate(my_list):
    my_list[i] = 2 * number

答案 4 :(得分:0)

The issue is that you are updating number not my_list. List comprehension is preferable, but here's an explicit way of doing the same thing that highlights where your problem is:

my_list = [1,9,3,8,5,7]
i=0

for number in my_list:
    # Your code here
    my_list[i]=2*number
    i += 1
print my_list

Good luck!