简体   繁体   English

在Python中的函数中传递列表

[英]Passing a list in a function in Python

I want to create a function which will receive a list, check each element of it and return a new list. 我想创建一个将接收列表的函数,检查它的每个元素并返回一个新列表。 If the element is greater than 97, it will put 100 in the new list. 如果该元素大于97,则它将100放入新列表中。 Otherwise, it will add three to the number and put it in the new list. 否则,它将在数字上加3,并将其放入新列表中。 At the function I just pass the list. 在功能上,我只是通过列表。 However, when I run it it doesn't return anything. 但是,当我运行它时,它不会返回任何内容。

Here is how I send the list to the function: 这是我将列表发送到函数的方式:

res=bonus(mark)

Here is my function: 这是我的功能:

def bonus(mark):
    new=[]
    for i in range(1,31):
        if (mark[i-1]>97):
            new.append(100)
        else:
            new.append(mark[i-1]+3)
    return new

You need to declare the function before calling it. 您需要在调用函数之前声明它。

For example: 例如:

mark = [1,97,3,4,98,6,99,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]

def bonus(mark):
    new=[]
    for i in range(1,31):
        if (mark[i-1]>97):
            new.append(100)
        else:
            new.append(mark[i-1]+3)
    return new

res=bonus(mark)

print(res)

outputs: 输出:

[4, 100, 6, 7, 100, 9, 100, 11, 12, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 3]

If you go through a list, do not use range(..) use for item in listname: 如果浏览列表,请不要对列表名称for item in listname:使用range(..)用法for item in listname:

def bonus(mark):
    new=[]
    for item in mark:  # item will be each element of mark in order, no need to indexaccess
        if (item > 97):
            new.append(100)
        else:
            new.append(item + 3)
    return new

Or shorten it to a list comprehension: 或将其简化为列表理解:

mark = list(range(80,100))

def bonus(m):
    return [min(100,m+3) for m in mark] # add m+3, if > 100 (for 98,99,100) use 100.

print (mark)
print (bonus(mark))

Output: 输出:

[80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 100, 100]

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

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