I have a bi dimensional list where the inner dimension always has 3 values (first 2 values are strings and the last is an integer) and the outer dimension just holds those values like so:
my_list=[["a","b",10],["c","d",12],["e","f",64]]
I have a function that attempts to append a new 3 value list to my_list. If the first and second value of that list matches the first and second value of a list currently in my_list I would like to add together their last (integer) value .
For example attempting to add ["a","b",3] to my_list would just change my_list like so:
my_list=[["a","b",13],["c","d",12],["e","f",64]]
However if attempting to add ["b","a",3] to my_list would just change my_list like so:
my_list=[["a","b",10],["c","d",12],["e","f",64], ["b","a",3]]
Here's my code:
my_list=[["a","b",10],["c","d",12],["e","f",64]]
a=["a","b",3]
for x in my_list:
if x[:2]==a[:2]:
x[3]=x[3]+a[3]
I get the following error:
Traceback (most recent call last):
File "./test", line 9, in
x[3]=x[3]+a[3]
IndexError: list index out of range
解决方案
List indexes in python are zero-based, as such your three-element lists are indexed by 0,1,and 2, not 1,2, and 3 as your code expects. Also, a dictionary with ("a","b") as keys may be a better data structure.