DAT BOI
DAT BOI

Reputation: 183

Python modifying and appending values to bi dimensional list

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 <module>
    x[3]=x[3]+a[3]

IndexError: list index out of range

Upvotes: 1

Views: 83

Answers (3)

B. M.
B. M.

Reputation: 18628

I suggest dictionaries, more efficient for such task :

my_dict={("a","b"):10,("c","d"):12, ("e","f"):64}

def add (key,value):
    if key not in my_dict: my_dict[key]=value
    else: my_dict[key]+=value

add(("a","b"),3)
add(("b","a"),3)  

print(my_dict)      

{('a', 'b'): 13, ('b', 'a'): 3, ('e', 'f'): 64, ('c', 'd'): 12}

Upvotes: 1

FullCombatBeard
FullCombatBeard

Reputation: 313

I think this is what you are trying to do, although it wont accept inputs, the functionality is fine

my_list=[["a","b",10],["c","d",12],["e","f",64]]

a=["a","b",3]

for x in my_list:
   if x[0] == a[0] and x[1] == a[1]:
      x[2] += a[2]

Upvotes: 2

pppery
pppery

Reputation: 3804

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.

Upvotes: 3

Related Questions