【问题标题】:builtins.TypeError: unsupported operand type(s) for -: 'list' and 'int'builtins.TypeError: 不支持的操作数类型 -: 'list' 和 'int'
【发布时间】:2019-02-17 09:52:23
【问题描述】:
builtins.TypeError: unsupported operand type(s) for -: 'list' and 'int'

为什么会出现这个错误?我有一个列表 b 的列表,我想从 b 的第一个列表的最后一个元素中减去 c。

sofar = abs(b[len(b[0])-1] - c)

【问题讨论】:

标签: python python-3.x


【解决方案1】:

list-of-lists b 中第一个列表的最后一个元素是(不需要len(LIST) - 1,-1 会得到最后一个元素就好了):

b[0][-1]

您可以从以下位置看到:

>>> x = [1,2,3]         # Three lists.
>>> y = [4,5,6]
>>> z = [7,8,9,10,11]
>>> b = [x,y,z]         # List of lists, [[1,2,3],[4,5,6],[7,8,9,10,11]].
>>> b[0][-1]            # Voilà ...
3

你可以用一个简单的修改它:

>>> b[0][-1] += 10
>>> b
[[1, 2, 13], [4, 5, 6], [7, 8, 9, 10, 11]]
#       ^^
#       Has had 10 added to it.

你拥有b[len(b[0])-1],是列表b[something],其中something是b[0]中最后一项的索引。这就是为什么它抱怨试图从列表中减去一个整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 2012-12-12
    • 2018-10-19
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多