【问题标题】:This is the sum problem between the elements in the list. Why does "None" come out?这是列表中元素之间的求和问题。为什么会出现“无”?
【发布时间】:2021-10-06 06:41:14
【问题描述】:
def add(t1, t2):
if len(t1) == len(t2):
    for i in range(len(t1)):
        [t1[i]+t2[i]]
elif len(t1) != len(t2):
    return None

t1 = [42, 1024, 23]
t2 = [6, 28, 496]
t3 = add(t1, t2)
print(t1)
print(t2)
print(t3)

列表中元素的问题对我来说太难了。 请给我一点帮助。

【问题讨论】:

  • 你只从你的函数中返回None,你为什么期望看到别的东西?同样[t1[i]+t2[i]] 构造一个列表然后丢弃它,实际上什么都不做。
  • 万一len(t1) == len(t2)你不返回任何东西
  • 你可以写return [(t1[i] + t2[i]) for i in range(len(t1))],虽然不是很优雅..

标签: python list function


【解决方案1】:

对于成对和的列表,您可以修改代码如下:

def add(t1, t2):
    if len(t1) == len(t2):
        result = []
        for i in range(len(t1)):
            result.append(t1[i]+t2[i])
        return result
    else:
        return None

当然,有一些实用工具可以缩短这个时间:

def add(t1, t2):
    if len(t1) == len(t2):
        return [*map(sum, zip(t1, t2))]
    # None returned implicitly

这个内置的加载代码可以解释为“将 sum 函数映射到 zip 生成的对上,并将结果和解压到一个列表中”。

查看一些文档:

【讨论】:

  • 使用解包你也可以提供t1..tn 而不是两个显式参数explicit
  • 我知道,但这会改变函数的功能以及它的签名参数结构。后者可以通过使用def add(*t) 进行补救。
【解决方案2】:

从 if 语句返回试试这个。

def add(t1, t2):
    if len(t1) == len(t2):
        return [(t1[i] + t2[i] ) for i in range(len(t1)) ]
    
    return None

【讨论】:

    【解决方案3】:

    或者简称:

    def add(t1, t2):
        return [sum(i) for i in zip(t1, t2)] if len(t1) == len(t2) else None
    

    甚至更短:

    def add(*x):
        return [*map(sum, zip(*x))] if set(map(len, x)) == 1 else None
    

    【讨论】:

      猜你喜欢
      • 2014-06-22
      • 1970-01-01
      • 2023-03-27
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 2018-02-13
      • 1970-01-01
      相关资源
      最近更新 更多