如何在包含元组作为元素的列表中使用map函数?

时间:2017-04-26 22:45:38

标签: python python-2.7 list python-3.x tuples

我正在尝试在元组列表中使用map函数。每个元组有三个元素,我想用嵌套测试元组中的每个元素,如下所示。

def decision(*sm):
    smoker=sm[0]
    age=sm[1]
    diet=sm[2]
    if smoker=="yes":
        if age<29.5:
            return "less risk"
        elif age>29.5:
            return "more risk"
    elif smoker=="no":
        if diet=="good":
            return "less risk"
        elif diet=="poor":
            return "more risk" 

health=[('yes', 21, 'poor'), ('no', 50, 'good')]
print list(map(decision,health))

它提供错误tuple index out of range

1 个答案:

答案 0 :(得分:2)

Python的map(..)将第一个参数视为函数(可调用),并在每次调用时传递第二个参数的一个元素(它迭代)。考虑到这一点,您必须进行以下修复:

删除变量参数,然后接受列表:

def decision(sm):  #Remove '*'