builtins.TypeError: unsupported operand type(s) for -: 'list' and 'int'
Why does it give this error? I have a list of list b and I want to subtract c from the last element of the first list of b.
sofar = abs(b[len(b[0])-1] - c)
The last element of the first list in the list-of-lists b
is (no need for len(LIST) - 1
, -1
will get the last element just fine):
b[0][-1]
You can see that from:
>>> 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
And you can modify it with a simple:
>>> b[0][-1] += 10
>>> b
[[1, 2, 13], [4, 5, 6], [7, 8, 9, 10, 11]]
# ^^
# Has had 10 added to it.
What you have, b[len(b[0])-1]
, is the list b[something]
, where something
is the index of the last item in b[0]
. That's why it's complaining about trying to subtract an integer from a list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.