【问题标题】:Filtering out odd numbers and squaring them in a tuple in Python在 Python 中过滤掉奇数并将它们平方成一个元组
【发布时间】:2020-09-23 16:39:17
【问题描述】:

这是一个学校作业的问题,感谢任何帮助指出我的错误。

首先,关于 Python 中的 map() 函数,我的任务是(不可选择)重新定义它以使其特定于一个元组:

def map(fn, seq):
    if seq == ():
        return ()
    else:
        return (fn(seq[0]),) + map(fn, seq[1:])

使用这个,我应该定义另一个函数square_odd(tuple),它接受一个包含整数的元组作为参数,并且只有当它们是奇数时才特别平方。本质上,对于 (5,6,7,8,9) 的元组输入,我应该返回 (25, 6, 49, 8, 81)。

我的想法是简单地利用lambda 编写一个函数,与if 配对以过滤掉奇数。这是我所拥有的:

def square_odd(tpl):
    return map(lambda x: x*x if x%2 == 0, tpl)

Python 在tpl 之前的逗号处返回了SyntaxError。谁能指出这可能是什么问题?我也必须写一个else 条件吗?我尝试添加else x,但只返回第一个值的整数值。

【问题讨论】:

    标签: python tuples


    【解决方案1】:

    那是因为你应该写else语句。

    map(lambda x: x*x if x%2 == 1 else x, tp1)
    

    并简单地尝试了此代码。而且你应该修复 x%2 == 0。 这个条件会找到偶数。

    return tuple(map(lambda x: x*x if x%2 == 1 else x, tp1))
    

    【讨论】:

      【解决方案2】:

      if 与 lambda 期望 else 语句。所以应该是这样的:

      def square_odd(tpl):
          return map(lambda x: x if x%2 == 0 else x*x, tpl)
      

      这意味着,如果x%2==0 是偶数,则取x,否则取x*x,它是正方形。

      【讨论】:

      • 非常感谢!我不知道还有其他必要的。非常感谢!
      【解决方案3】:
      def map(fn, seq):
          if seq == ():
              return ()
          else:
              return (fn(seq[0]),) + map(fn, seq[1:])
      
      def square_odd(tpl):
          return map(lambda x: x**2 if x%2 else x, tpl)
      
      t = (1,2,3,4,5)
      print(square_odd(t))
      
      
      

      我已经这样做了,输出是(1, 2, 9, 4, 25)。

      由于三元运算符A if condition else B 不能用作A if condition,因此引发语法错误

      【讨论】:

        猜你喜欢
        • 2021-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-02
        • 2020-07-03
        • 1970-01-01
        • 2021-08-18
        • 1970-01-01
        相关资源
        最近更新 更多