【问题标题】:Python function with double condition具有双重条件的 Python 函数
【发布时间】:2016-03-15 22:00:46
【问题描述】:

我想创建一个函数,它返回奇数位置的列表元素或列表的负元素。

我的解决方案适用于第一个断言,但第二个会生成 AssertionError,因为返回 [-1, -2, 1] 而不是 [-1, -2]。有什么建议吗?

def solution(input):
  output = []
  for item in input: 
    if item < 0:
        output.append(item)
    elif not item % 2 == 0:
        output.append(item)
  return output

assert solution([0,1,2,3,4,5]) == [1,3,5]
assert solution([1,-1,2,-2]) == [-1,-2]

【问题讨论】:

  • 为什么不是[-1,-2,1]? 1 是奇数...
  • @JoranBeasley 假设得到的数字要么是奇数要么是负数,所以[-1, -2, 1] 不正确

标签: python assertion


【解决方案1】:

您想要奇数位置的数字,但您的 % 检查是检查列表中的实际值而不是它们的位置。

尝试使用enumerate 在遍历列表时获取索引旁边的值:

def solution(input):
  output = []
  for ix, item in enumerate(input): 
    if item < 0 or ix % 2 != 0:
        output.append(item)
  return output

【讨论】:

    【解决方案2】:

    另外,出于完整性目的,您可能需要考虑将其添加到您现有的代码中:

        if any(i < 0 for i in output):
                return [i for i in output if i < 0]
    

    ,因为它测试是否存在否定,如果存在则只返回那些。然而,从我的角度来看,HumphreyTriscuit 的答案是更好的解决方案。

    【讨论】:

      【解决方案3】:

      一行定义解函数:

      def solution(input):
          return [input[pos] for pos in range(len(input)) if not pos %2 == 0 or input[pos] < 0]
      
      print solution([0,1,2,3,4,5,7])
      print solution([1,-1,2,-2, -3])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-10-01
        • 1970-01-01
        • 2021-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-05
        相关资源
        最近更新 更多