【问题标题】:How to use map function on a list which contains tuples as elements?如何在包含元组作为元素的列表上使用 map 函数?
【发布时间】:2017-04-26 22:45:38
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

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

    删除可变参数,并接受一个列表:

    def decision(sm):  #Remove '*'
    

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-17
      相关资源
      最近更新 更多