Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare a list to a list of tuple to get another list

Tags:

python

list

I am new to python so apologies for the naive question. I have a list

l1 = [2, 4, 6, 7, 8] 

and another list of tuples

l2 = [(4,6), (6,8), (8,10)]

I want to output a list l3 of size l1 that compares the value of l1 to the first co-ordinates of l2 and stores the second co-ordinate if the first co-ordinate is found in l1, else stores 0.

output :

l3 = [0, 6, 8, 0, 10]

I tired to do a for loop like:

l3 = []
for i in range(len(l1)):
   if l1[i] == l2[i][0]:
      l3.append(l2[i][1])
   else:
      l3.append(0)  

but this doesn't work. It gives the error

IndexError: list index out of range

which is obvious as l2 is shorter than l1.

like image 398
Jenny Avatar asked Jun 12 '18 19:06

Jenny


People also ask

Can you compare tuple and list?

The major difference between tuples and lists is that a list is mutable, whereas a tuple is immutable. This means that a list can be changed, but a tuple cannot.

Can you compare list and tuple in Python?

List and Tuple in Python are the classes of Python Data Structures. The list is dynamic, whereas the tuple has static characteristics. This means that lists can be modified whereas tuples cannot be modified, the tuple is faster than the list because of static in nature.

How do you compare two big lists in Python?

We can use the Python map() function along with functools. reduce() function to compare the data items of two lists. The map() method accepts a function and an iterable such as list, tuple, string, etc. as arguments.

How do you compare lists with sets?

Comparing lists in Python The set() function creates an object that is a set object. The cmp() function is used to compare two elements or lists and return a value based on the arguments passed. In the following sections, we will see the application of set() , cmp() , and difference() functions.


2 Answers

You can create a dictionary from l2:

l1 = [2,4,6,7,8] 
l2 =[(4,6),(6,8),(8,10)]
new_l2 = dict(l2)
l3 = [new_l2.get(i, 0) for i in l1]

Output:

l3 = [0,6,8,0,10]
like image 125
Ajax1234 Avatar answered Sep 22 '22 16:09

Ajax1234


I would always use Ajax1234's solution instead, but I wanted to illustrate how I would approach it using a for-loop, as you intended:

l3 = []
for elem in l1:
    pairs = list(filter(lambda x: x[0] == elem, l2))
    l3.append(pairs[0][1] if pairs else 0)

An alternate approach would be using next() and a list comprehension instead of filter() and a for-loop. This one is far more efficient and readable:

l3 = [next((u[1] for u in l2 if u[0] == elem), 0) for elem in l1]
like image 29
Mr. Xcoder Avatar answered Sep 23 '22 16:09

Mr. Xcoder