Associating two item in a list

I am comparing two lists for common strings and my code currently works to output items in common from two lists.

list1

['5', 'orange', '20', 'apple', '50', 'blender']


list2

['25', 'blender', '20', 'pear', '40', 'spatula']


Here is my code so far:

for item1 in list1[1::2]:
for item2 in list2[1::2]:
if item1 == item2:
print(item1)


This code would return blender. What I want to do now is to also print the number before the blender in each list to obtain an output similar to:

blender, 50, 25


I have tried to add two new lines to the for loop but did not have the desired output:

for item1 in list1[1::2]:
for item2 in list2[1::2]:
for num1 in list1[0::2]:
for num2 in list2[0::2]:
if item1 == item2:
print(item1, num1, num2)


I know now that making for loops is not the answer. Also trying to call item1[-1] does not work. I am new to Python and need some help with this!

Thank you

You can do it in two ways, either stay with lists (Which is more messy):

list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
for item1 in list1[1::2]:
for item2 in list2[1::2]:
if item1 == item2:
item_to_print = item1
print(item1, ",", end="")
for index in range(len(list1)):
if list1[index] == item1:
print(list1[index - 1], ",", end="")
for index in range(len(list2)):
if list2[index] == item1:
print(list2[index - 1])


or the better way (in my opinion) with dictionary:

dict1 = {'apple': '20', 'blender': '50', 'orange': '5'}
dict2 = {'blender': '25', 'pear': '20', 'spatula': '40'}
for item in dict1:
if item in dict2:
print(item, ",", dict1[item], ",", dict2[item])


Both will output:

>> blender , 50 , 25


You're approaching this problem with the wrong Data Structure. You shouldn't keep this data in lists if you're doing lookups between the two. Instead, it would be much easier to use a dictionary here.

Setup

You can use zip to create these two dictionaries:

a = ['5', 'orange', '20', 'apple', '50', 'blender']
b = ['25', 'blender', '20', 'pear', '40', 'spatula']

dct_a = dict(zip(a[1::2], a[::2]))
dct_b = dict(zip(b[1::2], b[::2]))


This will leave you with these two dictionaries:

{'orange': '5', 'apple': '20', 'blender': '50'}
{'blender': '25', 'pear': '20', 'spatula': '40'}




This makes every part of your problem easier to solve. For example, to find common keys:

common = dct_a.keys() & dct_b.keys()
# {'blender'}


And to find all the values matching each common key:

[(k, dct_a[k], dct_b[k]) for k in common]


Output:

[('blender', '50', '25')]


I think you'd be better suited using dictionaries for this problem..

dict1 = {'orange': 5, 'apple': 20, 'blender': 50}
dict2 = {'blender': 25, 'pear': 20, 'spatula': 40}


so to get the outputs you want

>>dict1['blender']
50
>>dict2['blender']
25


So if you want to get the number of blenders from each dictionary in the format you want, you can really just use

print("blender, "+str(dict1['blender'])+", "+str(dict2['blender']))


To take this one step further and output based on what's in dict1 and dict2

for i in dict1.keys(): #dict1.keys() is essentially a list with ['orange','apple','blender']
if i in dict2.keys(): #same deal, but different items in the list
print(str(i)+", "+str(dict1[i])+", "+str(dict2[i])) #this outputs items that are in BOTH lists
else:
print(str(i)+", "+str(dict1[i])) #this outputs items ONLY in dict1
for i in dict2.keys():
if i not in dict1.keys(): #we use not since we already output the matching in the previous loop
print(str(i)+", "+str(dict2[i])) #this outputs items ONLY in dict2


Outputs:

orange, 5
apple, 20
blender, 50, 25
pear, 20
spatula, 40


with enumerate you can solve your problem:

list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']



for n1, item1 in enumerate(list1[1::2]):
for n2, item2 in enumerate(list2[1::2]):
if item1 == item2:
print(list1[n1*2], list2[n2*2], item1)


enumerate returns a tuple where the first element is the count of the iteration, the second the element.
Since enumerate is counting the iteration and you're stepping 2, we need to multiply by 2:
orange will be the first iteration, so n1 will be 0, so the previous value is at index 0*2
apple will be in the second iteration, so n1 will be 1, so the previous value is at index 1*2
blender will be in the third iteration, so n1 will be 2, so the previousl value is at index 2*2.

this means that in for n1, item1 in enumerate(list1[1::2]): n1 and item1 will have this values:


Iteration 1: n1 = 0, item1 = orange, previous_index = 0*2
Iteration 2: n1 = 1, item1 = apple, previous_index = 1*2
Iteration 3: n1 = 2, item1 = blender, previous_index = 2*2


same goes for for n2, item2 in enumerate(list2[1::2])::


Iteration 1: n2 = 0, item2 = blender, previous_index = 0*2
Iteration 2: n2 = 1, item2 = pear, previous_index = 1*2
Iteration 3: n2 = 2, item2 = spatula, previous_index = 2*2


Assuming the nouns in your lists are unique (per list), create dictionaries out of your lists first.

In [1]: list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
In [2]: list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
In [3]:
In [3]: dict1 = dict(reversed(pair) for pair in zip(*[iter(list1)]*2))
In [4]: dict2 = dict(reversed(pair) for pair in zip(*[iter(list2)]*2))
In [5]:
In [5]: dict1
Out[5]: {'apple': '20', 'blender': '50', 'orange': '5'}
In [6]: dict2
Out[6]: {'blender': '25', 'pear': '20', 'spatula': '40'}


This code leverages the grouper recipe from the itertools docs.

Matching two items from your dictionaries is easy as pie.

In [7]: key = 'blender'
In [8]: print(key, dict1[key], dict2[key])
blender 50 25


You could even build a dictionary that holds the common keys from dict1 and dict2 and a list of the values.

In [12]: common = dict1.keys() & dict2
In [13]: {c:[dict1[c], dict2[c]] for c in common}
Out[13]: {'blender': ['50', '25']}


For an arbitrary number of dicts, you can abstract this further.

In [28]: from functools import reduce
In [29]: from operator import and_
In [30]:
In [30]: dicts = (dict1, dict2)
In [31]: common = reduce(and_, map(set, dicts))
In [32]: {c:[d[c] for d in dicts] for c in common}
Out[32]: {'blender': ['50', '25']}


I hope this code will work for you.

l1 =['5', 'orange', '20', 'apple', '50', 'blender']
l2 = ['25', 'blender', '20', 'pear', '40', 'spatula']

for list1_item in zip(*[iter(l1)]*2):
for list2_item in zip(*[iter(l2)]*2):
if list1_item[1]==list2_item[1]:
print list1_item[1],list1_item[0],list2_item[0]


it will print output

blender 50 25

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue