首页 > 解决方案 > 如何在 python 中使用 if else 语句将列表放入函数中以创建变量?

问题描述

我如何让这些列表通过我的函数(这是正确的术语)?

列表:

temp_a = [1, 2, 3, 4, 5]
temp_b = [2, 2, 3, 4, 1]
temp_c = [1, 0, 2, 2, 1]

函数(这里我只是放了*,但我想在函数中定义列表):

def temp_class(temperature):
temp_class = []
for i in *:
    if i < 3:
        temp_class.append(0)
    else:
        temp_class.append(1)

不起作用的示例:

temp_value = [tempclass(t) for t in temp_a] #initial function is wrong
print(temp_value)

这里有什么问题?我试图查看 Stack Overflow 和其他地方,但找不到任何东西。也许我使用了错误的术语。

我用什么代替*?

标签: pythonpython-3.xlistfunctionif-statement

解决方案


我猜你正在寻找星号参数:

def foo(*args, **kwargs):
    print(args)
    print(kwargs)

测试:

foo([1,2,3], bar1="foobar", bar2="foobar2" )

([1, 2, 3],)
{'bar1': 'foobar', 'bar2': 'foobar2'}

推荐阅读