繁体   English   中英

Python 列表作为函数参数

[英]Python list as function argument

我的目标是尝试返回列表中所有具有偶数位置的值。 以下是我的python代码。 我不知道我应该更新哪个部分。 请帮忙!! 谢谢

def evenValue(numbers):
    results = []
    for x in numbers:
        if results.index(x) %2 ==0:
            results.append(x)
    return results

我的错误信息是

> Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    evenValue([1,2,3,4,5,6])
  File "<pyshell#6>", line 4, in evenValue
    if results.index(x) %2 ==0:
ValueError: 1 is not in list

尝试这个。 切片采用偶数元素。

def evenValue(numbers):
    return numbers[0::2]

或更短:

evenValue=lambda numbers: numbers[0::2]
def evenValue(numbers):
    results = []
    for x in numbers:
        if numbers.index(x) %2 ==0:   #Use 'numbers' list instead of 'results' list
            results.append(x)
    return results
print(evenValue([1,2,3,4,5,6,7]))

输出

[1, 3, 5, 7]

使用列表理解:

lst = list(range(50))
even_indexes = lambda numbers: [lst[i] for i in range(len(lst)) if i%2==0]
even_indexes(lst)

暂无
暂无

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

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