Counting frequencies in two lists, Python

I am new to python programming, so please carry over my question with a newbie ...

I have one starting list (list1), which I cleared for duplicates, and eventually a list appears with one of each value (list2):

list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16],

list2 = [13, 19, 2, 16, 6, 5, 20, 21]

I want to count how many times each of the values ​​in "list2" appears in "list1", but I cannot figure out how to do this without making a mistake.

The result I'm looking for looks like this:

The number 13 is presented 1 time in the list1. ........ Number 16 is presented 2 times in the list1.

+4
source share
6

- :

from collections import Counter
list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16]
c = Counter(list1)
print(c)

Counter({2: 1, 5: 1, 6: 1, 13: 4, 16: 2, 19: 3, 20: 2, 21: 1})

, - , , , dicts:

for k, v in c.items():
    print('- Element {} has {} occurrences'.format(k, v))

:

- Element 16 has 2 occurrences
- Element 2 has 1 occurrences
- Element 19 has 3 occurrences
- Element 20 has 2 occurrences
- Element 5 has 1 occurrences
- Element 6 has 1 occurrences
- Element 13 has 4 occurrences
- Element 21 has 1 occurrences
+7
visited = []
for i in list2:
  if i not in visited:
    print "Number", i, "is presented", list1.count(i), "times in list1"
    visited.append(i)
+6

, , , - - ( ) 1:

list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16]

frequency_list = {}

for l in list1:
    if l in frequency_list:
        frequency_list[l] += 1
    else:
        frequency_list[l] = 1

print(frequency_list)

:

{
    16: 2,
    2: 1,
    19: 3,
    20: 2,
    5: 1,
    6: 1,
    13: 4,
    21: 1
}

16 , 2 - ...

+1

>>> list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16],
>>> list2 = [13, 19, 2, 16, 6, 5, 20, 21]

>>> import operator
>>> for s in list2:
...    print s, 'appearing in :',  operator.countOf(list1, s)
0

list "" "". Python , (str), (int) , google. , , , "". , .

. count(). , 13 1:

count_13 = list1.count(13)

for :

for x in list2:
    print(list1.count(x)) #This is for python version 3 and up

python 3:

for x in list2:
    print list1.count(x)
0

You do not need to delete duplicates. When you add to the dictionary, automatically duplicates will be considered as separate values.

list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16]
counts = {s:list1.count(s) for s in list1}
print counts

{2: 1, 5: 1, 6: 1, 13: 4, 16: 2, 19: 3, 20: 2, 21: 1}
0
source

Source: https://habr.com/ru/post/1655112/


All Articles