【问题标题】:Why wont this code allow me to subtract two lists in python?为什么这段代码不允许我在 python 中减去两个列表?
【发布时间】:2016-11-15 15:13:46
【问题描述】:

我有两个列表,想从对面列表中的对应元素中减去每个元素。当我写这段代码时:

list(map(sub, irrad_fore, irrad_exp))

我收到以下错误:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

这是为什么?

【问题讨论】:

  • 你不能从一个字符串中减去一个字符串。将列表中的元素转换为整数,然后可以减去它们。

标签: python list subtraction


【解决方案1】:

正如错误清楚地表明,你不能直接减去两个str。为了实现这一点,您必须首先将str 对象转换为int。而不是map(),更好的方法是在两个列表上写列表理解zip()

>>> a = ['1', '4', '7', '9']
>>> b = ['3', '3', '7', '11']
>>> [int(i) - int(j) for i, j in zip(a, b)]
[-2, 1, 0, -2]

【讨论】:

    猜你喜欢
    • 2012-03-06
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    相关资源
    最近更新 更多