I’ve created two lists, call them “a” and “b”. List a has length 24,480 while b has length 20,116. Every element in both a and b is also a list of length 3. To visualize, each element of these lists looks like:
a = [str1a, str2a, float1a]
b = [str1b, str2b, float1b]
What I need to do is be able to check if str1a == str1b
and str2a == str2b
, then change the value of float1a
resulting in float1a * float1b
. There are some duplicates in List b
and not every element will necessarily have a match.
I tried this using a loop, which works and gets what I need.
for i in range(0, len(a)):
for n in range(0, len(b)):
if a[i][0] == b[n][0] and a[i][1] == b[n][1]:
a[i][2] *= b[n][2]
What I would love, however, is to be able to get the same result, but in a (quicker) more efficient way. Ideally, I stick with python-based methods – I’d rather not solve this by importing any modules.
joetjen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
for each element in listA, you are looking all element in listB and then checking if value at 2 indices are same or not. if yes then updating indices 3 value. with this approach you are doing O(N*M)
you can reduce lookup, by make a unique hash of 2 indices, and have all the index in it as value. and when you are traversing the listB, then you will make hash of first two indices and see if that hash exists or not in the dictionary of listA hash. if yes, then for all indices apply the multiplicatio n logic
from collections import defaultdict
listA = [['a', 'b',2], ['c', 'd', 3]]
listB = [['a', 'b',3], ['a','b', 3]]
dic = defaultdict(list)
for index, (a,b, c) in enumerate(listA):
key = (a, b)
dic[key].append(index)
dic2 = defaultdict(lambda : 1)
for index, (a, b, c) in enumerate(listB):
key = (a, b)
dic2[key] *= c
print(dic, dic2)
for key, value in dic2.items():
if key in dic:
for index in dic[key]:
listA[index][2] *= value
print(listA) # [['a', 'b', 18], ['c', 'd', 3]]
edit: using tuple (a, b) as key and defaultdict
for dic
as suggested by @Barmar
4