简体   繁体   English

Python根据值是奇数还是偶数来更改列表元素

[英]Python changing list element based on value being odd or even

Supposed to change a value of a list based on if the value is odd or even. 假设根据值是奇数还是偶数来更改列表的值。 Error: 错误:

list assignment index out of range 

Code: 码:

def list_mangler(list_in):
    for i in list_in:
        if i % 2 == 0:
            list_in[i] = i * 2
        else:
            list_in[i] = i * 3
    return list_in



list_mangler([1, 2, 3, 4])

the problem is that for i in list_in yields items in the list, not indices . 问题是, for i in list_infor i in list_in产生的是列表中的项目 ,而不是index To get the indices, use enumerate : 要获取索引,请使用enumerate

for i, val in enumerate(list_in):
    if i % 2 == 0:
        list_in[i] = val * 2
    ...

If you wanted to return a new list (rather than mutating the old list), a list comprehension with a conditional expression could do nicely: 如果您想返回一个列表(而不是突变旧列表),那么使用条件表达式进行列表理解可以很好地实现:

[val * 3 if val % 2 else val * 2 for val in list_in]

And of course, you can use this with slice assignment to mutate list_in if you really need to: 当然,如果确实需要,可以将其与切片分配一起使用来对list_in进行突变:

list_in[:] = [val * 3 if val % 2 else val * 2 for val in list_in]

As a point of style, if your function's purpose is to modify the list in place, don't return the list. 作为一种风格,如果函数的目的是在适当位置修改列表,请不要返回列表。 That makes it clear that the input was mutated rather than returning a new list that was somehow constructed from the data in the original. 这清楚地表明,输入是突变的,而不是返回由原始数据以某种方式构造的新列表。

You need use enumerate , because for i in list returns the element not the index. 您需要使用enumerate ,因为for i in list返回元素而不是索引。

for index, val in enumerate(list_in):
        if val % 2 == 0:
            list_in[index] = val* 2
        else:
            list_in[index] = val * 3
    return list_in

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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