How do I check which items in List2 are in List1, then their count and order

Asked

Viewed 80 times

-5

I am a beginner in Python and I would like to count on your help for the problems below. I have worked on two lists as the following objectives: 1.Check which items in List2 are in List1 2.Count each List2 item in List1 and sort it in Orderly List2.

Lista1 = ['a', 'k', 'j', 'd', 'p', 'u', 'j', 'h', 'k', 'k', 'c', 'p', 'e', 'u', 'z', 'z', 'f', 's', 'u', 'k', 'p', 'u', 'j', 'h', 'b', 'k', 'j', 'd', 'e', 'u', 'j', 'z']

Lista2 = ['j', 'u', 'z', 'k', 'u', 'p']

Lista_ordenada = [ ]


for i in  Lista1:
  if i == 'j' :
    break
Lista_ordenada.append('j')
.
.
.
for i in  Lista1:
  if i == 'p' :
    break
Lista_ordenada.append('p')

Of problems:

  1. Although the code works, I see that it is very repetitive and slow;
  2. Although I managed to put them in the ordered list (in a disorderly way), I could not do the count, nor order them.

Any help will be welcome.

2 answers

0

I believe the solution below meets your need:

Input:

lista1 = ['a', 'k', 'j', 'd', 'p', 'u', 'j', 'h', 'k', 'k', 'c', 'p', 'e', 'u', 'z', 'z', 'f', 's', 'u', 'k', 'p', 'u', 'j', 'h', 'b', 'k', 'j', 'd', 'e', 'u', 'j', 'z']
lista2 = ['j', 'u', 'z', 'k', 'u', 'p']
lista_ordenada = []

for i in  lista2:
  if i in lista1:
    item_tuple = (i, lista1.count(i))
    lista_ordenada.append(item_tuple)
 
lista_ordenada = sorted(lista_ordenada, key=lambda tup: tup[1], reverse = True)
print(lista_ordenada)

Output:

[('j', 5), ('u', 5), ('k', 5), ('u', 5), ('z', 3), ('p', 3)]

The For loop checks if each item in List2 is in List1 and, if so, creates a tuple (item_tuple) of the item itself (i) with the number of occurrences (list1.Count(i)).

After creating the tuple, it adds this set in the sorted list via the . append(item_tuple).

Finally, the function Sorted() sorts the list_ordered by the second tuple item, which is the number of occurrences. Reverse = True was used to sort decreasingly, since the default function is the ascending sort.

0

The approach you used is not the most efficient because for each element of Lista2 you had to write a specific code to perform the comparison and addition of the element to Lista_ordenada, case Lista2 its code would no longer fulfill its purpose and would have to be written a new comparison loop for the new element. Another clear thing is the question of performance checking Lista1 is repeated making the algorithm inefficient.

Re-examined the question, there are three problems:

  1. Check which items from Lista2 are in the Lista1.
  2. Count each item of the Lista2 in Lista1.
  3. Sort items in the Lista_ordenada.

To check which items of Lista2 are in the Lista1 transform them into ensembles and make the intercession with the operator &.

To count each item of the Lista2 in Lista1 brood accountants and use only those elements that are in Lista_ordenada to filter the result (because its elements are common the two lists).

To sort items in Lista_ordenada use the built-in function sorted().

from collections import Counter

Lista1 = ['a', 'k', 'j', 'd', 'p', 'u', 'j', 'h', 'k', 'k', 'c', 'p', 'e', 'u', 'z', 'z', 'f', 's', 'u', 'k', 'p', 'u', 'j', 'h', 'b', 'k', 'j', 'd', 'e', 'u', 'j', 'z']
Lista2 = ['j', 'u', 'z', 'k', 'u', 'p']

#Faz a intercessão de Lista1 e Lista2 e ordena o resultado.
Lista_ordenada = sorted(set(Lista1) & set(Lista2))

#Conta a frequencia de cada elemento de Lista1 e Lista2.
Contagem1 = Counter(Lista1)
Contagem2 = Counter(Lista2)

print(f"Elementos comuns as duas listas {Lista_ordenada}")

for k in Lista_ordenada:
  print(f"O elemento '{k}' aparece {Contagem1[k]} vez{'es' if Contagem1[k]>1 else '' } na lista1.")
  print(f"O elemento '{k}' aparece {Contagem2[k]} vez{'es' if Contagem2[k]>1 else '' } na lista2.")
  print(f"Num total de {Contagem1[k] + Contagem2[k]} aparições.")

#Elementos comuns as duas listas ['j', 'k', 'p', 'u', 'z']
#O elemento 'j' aparece 5 vezes na lista1.
#O elemento 'j' aparece 1 vez na lista2.
#Num total de 6 aparições
#O elemento 'k' aparece 5 vezes na lista1.
#O elemento 'k' aparece 1 vez na lista2.
#Num total de 6 aparições
#O elemento 'p' aparece 3 vezes na lista1.
#O elemento 'p' aparece 1 vez na lista2.
#Num total de 4 aparições
#O elemento 'u' aparece 5 vezes na lista1.
#O elemento 'u' aparece 2 vezes na lista2.
#Num total de 7 aparições
#O elemento 'z' aparece 3 vezes na lista1.
#O elemento 'z' aparece 1 vez na lista2.
#Num total de 4 aparições

Test the code on Ideone

  • It sounds interesting your exposure, but that’s not exactly it. Correction: In Lista2 there is only one 'u'. In the second problem, I ask to be seen the count (occurrences of elements) of List2 in List1. Ex: 'j' occurs 5 times in List1. Then 'j' must be inserted in a new List in order from > to <, for example: Sorted list = ['j', 'k'...] If the solution comes in the form of a better function, because if List2 has fewer elements, these will be exposed in a new order.

  • @Oberdansantos Look your question is written Lista2 = ['j', 'u', 'z', 'k', 'u', 'p'] in your question the element u is repeated twice,

  • @Oberdansantos, the question is written Count each List2 item in List1 and sort it in Orderly List2. does not speak at any time that it is to order based on its frequency.

  • @Oberdansantos I can only answer what was asked, I can’t guess your intentions and objectives if you don’t express them.

  • I apologize for not expressing myself correctly. I know that we need a logic of the problem to solve it. I believe it has now become clear and that you can help me.

  • @Oberdansantos Not my time is expensive and this is pro bono. I answered what was written if not written correctly open another question for someone else to answer it.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.