Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

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]

Solution 3:

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}

Post a Comment for "Python Modifying And Appending Values To Bi Dimensional List"