Jak mogę zliczyć wystąpienia elementu listy?
Biorąc pod uwagę element, Jak mogę policzyć jego wystąpienia na liście w Pythonie?
26 answers
Jeśli chcesz liczyć tylko jeden element, użyj metody count
:
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Nie używaj tego, jeśli chcesz policzyć wiele elementów. Wywołanie count
W pętli wymaga oddzielnego przejścia nad listą dla każdego wywołania count
, co może być katastrofalne dla wydajności. Jeśli chcesz policzyć wszystkie elementy, a nawet kilka, użyj Counter
, Jak wyjaśniono w pozostałych odpowiedziach.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 21:48:15
Użycie Counter
Jeśli używasz Pythona 2.7 lub 3.x i chcesz liczbę wystąpień dla każdego elementu:
>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-24 17:46:30
Zliczanie wystąpień jednej pozycji na liście
Do zliczania wystąpień tylko jednego elementu listy możesz użyć count()
>>> l = ["a","b","b"]
>>> l.count("a")
1
>>> l.count("b")
2
Liczenie wystąpień wszystkich pozycji na liście jest również znane jako "liczenie" listy lub tworzenie licznika tally.
Zliczanie wszystkich elementów za pomocą count()
Do liczenia wystąpień elementów w l
można po prostu użyć rozumienia listy i metody count()
[[x,l.count(x)] for x in set(l)]
(lub podobnie ze słownikiem dict((x,l.count(x)) for x in set(l))
)
Przykład:
>>> l = ["a","b","b"]
>>> [[x,l.count(x)] for x in set(l)]
[['a', 1], ['b', 2]]
>>> dict((x,l.count(x)) for x in set(l))
{'a': 1, 'b': 2}
Liczenie wszystkich pozycji z licznikiem()
Alternatywnie, jest szybsza Counter
klasa z collections
biblioteki
Counter(l)
Przykład:
>>> l = ["a","b","b"]
>>> from collections import Counter
>>> Counter(l)
Counter({'b': 2, 'a': 1})
Ile szybciej jest Licznik?
Sprawdziłam, o ile szybciej {[11] } jest do liczenia list. Wypróbowałem obie metody z kilkoma wartościami n
i wydaje się, że {[11] } jest szybsza o stały współczynnik w przybliżeniu 2.
Oto skrypt, którego użyłem:
from __future__ import print_function
import timeit
t1=timeit.Timer('Counter(l)', \
'import random;import string;from collections import Counter;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
)
t2=timeit.Timer('[[x,l.count(x)] for x in set(l)]',
'import random;import string;n=1000;l=[random.choice(string.ascii_letters) for x in range(n)]'
)
print("Counter(): ", t1.repeat(repeat=3,number=10000))
print("count(): ", t2.repeat(repeat=3,number=10000)
I wyjście:
Counter(): [0.46062711701961234, 0.4022796869976446, 0.3974247490405105]
count(): [7.779430688009597, 7.962715800967999, 8.420845870045014]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:10:29
Inny sposób, aby uzyskać liczbę wystąpień każdego elementu, w słowniku:
dict((i, a.count(i)) for i in a)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-31 12:21:20
list.count(x)
zwraca liczbę razy x
pojawia się na liście
Zobacz: http://docs.python.org/tutorial/datastructures.html#more-on-lists
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-24 13:20:02
Biorąc pod uwagę element, Jak mogę policzyć jego wystąpienia na liście w Pythonie?
Oto przykładowa lista:
>>> l = list('aaaaabbbbcccdde')
>>> l
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
list.count
Jest metoda list.count
>>> l.count('b')
4
To działa dobrze dla każdej listy. Krotki mają również tę metodę:
>>> t = tuple('aabbbffffff')
>>> t
('a', 'a', 'b', 'b', 'b', 'f', 'f', 'f', 'f', 'f', 'f')
>>> t.count('f')
6
collections.Counter
I są jeszcze Kolekcje.Licznik. Możesz wrzucić dowolne iterable do licznika, a nie tylko listy, a licznik zachowa strukturę danych z liczników żywioły.
Użycie:
>>> from collections import Counter
>>> c = Counter(l)
>>> c['b']
4
Liczniki są oparte na słownikach Pythona, ich klucze są elementami, więc klucze muszą być hashable. Są one w zasadzie jak zestawy, które pozwalają na redundantne elementy do nich.
Dalsze wykorzystanie collections.Counter
Możesz dodawać lub odejmować iterable z licznika:
>>> c.update(list('bbb'))
>>> c['b']
7
>>> c.subtract(list('bbb'))
>>> c['b']
4
I możesz również wykonywać operacje wielostanowiskowe z licznikiem:
>>> c2 = Counter(list('aabbxyz'))
>>> c - c2 # set difference
Counter({'a': 3, 'c': 3, 'b': 2, 'd': 2, 'e': 1})
>>> c + c2 # addition of all elements
Counter({'a': 7, 'b': 6, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c | c2 # set union
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1, 'y': 1, 'x': 1, 'z': 1})
>>> c & c2 # set intersection
Counter({'a': 2, 'b': 2})
Dlaczego nie pandy?
Kolejna odpowiedź sugeruje:
Dlaczego nie używać pand?
Pandas jest biblioteką powszechną, ale nie znajduje się w bibliotece standardowej. Dodanie go jako wymogu nie jest trywialne.
Istnieją wbudowane rozwiązania dla tego przypadku użycia zarówno w samym obiekcie list, jak i w bibliotece standardowej.
Jeśli twój projekt nie wymaga pand, byłoby głupotą uczynić go wymaganiem tylko dla tej funkcjonalności.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55
Jeśli chcesz policzyć wszystkie wartości na raz możesz to zrobić bardzo szybko używając tablic numpy i bincount
w następujący sposób
import numpy as np
a = np.array([1, 2, 3, 4, 1, 4, 1])
np.bincount(a)
Co daje
>>> array([0, 3, 1, 1, 2])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-19 10:53:07
Porównałem wszystkie proponowane rozwiązania (i kilka nowych) z perfplot (mój mały projekt).
Licząc Jeden element
Dla wystarczająco dużych tablic okazuje się, że
numpy.sum(numpy.array(a) == 1)
Jest nieco szybszy od innych rozwiązań.
Liczenie wszystkich pozycji
numpy.bincount(a)
Tego właśnie chcesz.
Kod do odtworzenia działki:
from collections import Counter
from collections import defaultdict
import numpy
import operator
import pandas
import perfplot
def counter(a):
return Counter(a)
def count(a):
return dict((i, a.count(i)) for i in set(a))
def bincount(a):
return numpy.bincount(a)
def pandas_value_counts(a):
return pandas.Series(a).value_counts()
def occur_dict(a):
d = {}
for i in a:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
return d
def count_unsorted_list_items(items):
counts = defaultdict(int)
for item in items:
counts[item] += 1
return dict(counts)
def operator_countof(a):
return dict((i, operator.countOf(a, i)) for i in set(a))
perfplot.show(
setup=lambda n: list(numpy.random.randint(0, 100, n)),
n_range=[2**k for k in range(20)],
kernels=[
counter, count, bincount, pandas_value_counts, occur_dict,
count_unsorted_list_items, operator_countof
],
equality_check=None,
logx=True,
logy=True,
)
2.
from collections import Counter
from collections import defaultdict
import numpy
import operator
import pandas
import perfplot
def counter(a):
return Counter(a)
def count(a):
return dict((i, a.count(i)) for i in set(a))
def bincount(a):
return numpy.bincount(a)
def pandas_value_counts(a):
return pandas.Series(a).value_counts()
def occur_dict(a):
d = {}
for i in a:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
return d
def count_unsorted_list_items(items):
counts = defaultdict(int)
for item in items:
counts[item] += 1
return dict(counts)
def operator_countof(a):
return dict((i, operator.countOf(a, i)) for i in set(a))
perfplot.show(
setup=lambda n: list(numpy.random.randint(0, 100, n)),
n_range=[2**k for k in range(20)],
kernels=[
counter, count, bincount, pandas_value_counts, occur_dict,
count_unsorted_list_items, operator_countof
],
equality_check=None,
logx=True,
logy=True,
)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-13 10:32:48
Jeśli możesz użyć pandas
, to value_counts
jest tam na ratunek.
>>> import pandas as pd
>>> a = [1, 2, 3, 4, 1, 4, 1]
>>> pd.Series(a).value_counts()
1 3
4 2
3 1
2 1
dtype: int64
Automatycznie sortuje wynik na podstawie częstotliwości, jak również.
Jeśli chcesz, aby wynik był na liście listy, wykonaj jak poniżej
>>> pd.Series(a).value_counts().reset_index().values.tolist()
[[1, 3], [4, 2], [3, 1], [2, 1]]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-31 10:04:08
Dlaczego nie używać pand?
import pandas as pd
l = ['a', 'b', 'c', 'd', 'a', 'd', 'a']
# converting the list to a Series and counting the values
my_count = pd.Series(l).value_counts()
my_count
Wyjście:
a 3
d 2
b 1
c 1
dtype: int64
Jeśli szukasz liczby określonego elementu, powiedzmy a , spróbuj:
my_count['a']
Wyjście:
3
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-29 21:19:42
Miałem ten problem dzisiaj i walcowane własne rozwiązanie, zanim pomyślałem, aby sprawdzić. To:
dict((i,a.count(i)) for i in a)
Jest bardzo, bardzo powolny dla dużych list. Moje rozwiązanie
def occurDict(items):
d = {}
for i in items:
if i in d:
d[i] = d[i]+1
else:
d[i] = 1
return d
Jest w rzeczywistości nieco szybsze niż rozwiązanie licznika, przynajmniej dla Pythona 2.7.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-07 19:18:54
# Python >= 2.6 (defaultdict) && < 2.7 (Counter, OrderedDict)
from collections import defaultdict
def count_unsorted_list_items(items):
"""
:param items: iterable of hashable items to count
:type items: iterable
:returns: dict of counts like Py2.7 Counter
:rtype: dict
"""
counts = defaultdict(int)
for item in items:
counts[item] += 1
return dict(counts)
# Python >= 2.2 (generators)
def count_sorted_list_items(items):
"""
:param items: sorted iterable of items to count
:type items: sorted iterable
:returns: generator of (item, count) tuples
:rtype: generator
"""
if not items:
return
elif len(items) == 1:
yield (items[0], 1)
return
prev_item = items[0]
count = 1
for item in items[1:]:
if prev_item == item:
count += 1
else:
yield (prev_item, count)
count = 1
prev_item = item
yield (item, count)
return
import unittest
class TestListCounters(unittest.TestCase):
def test_count_unsorted_list_items(self):
D = (
([], []),
([2], [(2,1)]),
([2,2], [(2,2)]),
([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
)
for inp, exp_outp in D:
counts = count_unsorted_list_items(inp)
print inp, exp_outp, counts
self.assertEqual(counts, dict( exp_outp ))
inp, exp_outp = UNSORTED_WIN = ([2,2,4,2], [(2,3), (4,1)])
self.assertEqual(dict( exp_outp ), count_unsorted_list_items(inp) )
def test_count_sorted_list_items(self):
D = (
([], []),
([2], [(2,1)]),
([2,2], [(2,2)]),
([2,2,2,2,3,3,5,5], [(2,4), (3,2), (5,2)]),
)
for inp, exp_outp in D:
counts = list( count_sorted_list_items(inp) )
print inp, exp_outp, counts
self.assertEqual(counts, exp_outp)
inp, exp_outp = UNSORTED_FAIL = ([2,2,4,2], [(2,3), (4,1)])
self.assertEqual(exp_outp, list( count_sorted_list_items(inp) ))
# ... [(2,2), (4,1), (2,1)]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-24 18:41:29
Poniżej znajdują się trzy rozwiązania:
Najszybsze jest użycie pętli for i zapisanie jej w Dict.
import time
from collections import Counter
def countElement(a):
g = {}
for i in a:
if i in g:
g[i] +=1
else:
g[i] =1
return g
z = [1,1,1,1,2,2,2,2,3,3,4,5,5,234,23,3,12,3,123,12,31,23,13,2,4,23,42,42,34,234,23,42,34,23,423,42,34,23,423,4,234,23,42,34,23,4,23,423,4,23,4]
#Solution 1 - Faster
st = time.monotonic()
for i in range(1000000):
b = countElement(z)
et = time.monotonic()
print(b)
print('Simple for loop and storing it in dict - Duration: {}'.format(et - st))
#Solution 2 - Fast
st = time.monotonic()
for i in range(1000000):
a = Counter(z)
et = time.monotonic()
print (a)
print('Using collections.Counter - Duration: {}'.format(et - st))
#Solution 3 - Slow
st = time.monotonic()
for i in range(1000000):
g = dict([(i, z.count(i)) for i in set(z)])
et = time.monotonic()
print(g)
print('Using list comprehension - Duration: {}'.format(et - st))
Wynik
#Solution 1 - Faster
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 234: 3, 23: 10, 12: 2, 123: 1, 31: 1, 13: 1, 42: 5, 34: 4, 423: 3}
Simple for loop and storing it in dict - Duration: 12.032000000000153
#Solution 2 - Fast
Counter({23: 10, 4: 6, 2: 5, 42: 5, 1: 4, 3: 4, 34: 4, 234: 3, 423: 3, 5: 2, 12: 2, 123: 1, 31: 1, 13: 1})
Using collections.Counter - Duration: 15.889999999999418
#Solution 3 - Slow
{1: 4, 2: 5, 3: 4, 4: 6, 5: 2, 34: 4, 423: 3, 234: 3, 42: 5, 12: 2, 13: 1, 23: 10, 123: 1, 31: 1}
Using list comprehension - Duration: 33.0
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-02 08:43:50
Liczba wszystkich elementów z itertools.groupby()
Antoher możliwość uzyskania liczby wszystkich elementów na liście może być za pomocą itertools.groupby()
.
Z liczbą "duplikatów"
from itertools import groupby
L = ['a', 'a', 'a', 't', 'q', 'a', 'd', 'a', 'd', 'c'] # Input list
counts = [(i, len(list(c))) for i,c in groupby(L)] # Create value-count pairs as list of tuples
print(counts)
Zwraca
[('a', 3), ('t', 1), ('q', 1), ('a', 1), ('d', 1), ('a', 1), ('d', 1), ('c', 1)]
Zauważ, jak połączyła pierwsze trzy a
jako pierwszą grupę, podczas gdy inne grupy a
są obecne w dalszej części listy. Dzieje się tak, ponieważ lista wejściowa L
nie została posortowana. Może to być czasem korzystne, jeśli grupy powinny w rzeczywistości rozdzielcie się.
Z unikalnymi licznikami
Jeśli wymagane jest unikalne zliczanie grup, po prostu posortuj listę wejściową:
counts = [(i, len(list(c))) for i,c in groupby(sorted(L))]
print(counts)
Zwraca
[('a', 5), ('c', 1), ('d', 2), ('q', 1), ('t', 1)]
Uwaga: do tworzenia unikalnych liczeń, wiele innych odpowiedzi zapewnia łatwiejszy i bardziej czytelny kod w porównaniu do rozwiązania groupby
. Ale pokazano tutaj, aby narysować równoległy do przykładu duplicate count.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-25 18:15:17
Sugerowano użycie bincount numpy , jednak działa tylko dla tablic 1d z nieujemnymi liczbami całkowitymi. Również wynikowa tablica może być myląca(zawiera wystąpienia liczb całkowitych od min do max oryginalnej listy i ustawia brakujące liczby całkowite na 0).
Lepszym sposobem na zrobienie tego z numpy jest użycie unique funkcji z atrybutem return_counts
ustawionym na True. Zwraca krotkę z tablicą unikalnych wartości i tablicą wystąpienia każdej unikalnej wartości.
# a = [1, 1, 0, 2, 1, 0, 3, 3]
a_uniq, counts = np.unique(a, return_counts=True) # array([0, 1, 2, 3]), array([2, 3, 1, 2]
I wtedy możemy je sparować jako
dict(zip(a_uniq, counts)) # {0: 2, 1: 3, 2: 1, 3: 2}
Działa również z innymi typami danych i "listami 2d", np.
>>> a = [['a', 'b', 'b', 'b'], ['a', 'c', 'c', 'a']]
>>> dict(zip(*np.unique(a, return_counts=True)))
{'a': 3, 'b': 3, 'c': 2}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-21 22:04:14
Aby policzyć liczbę różnych elementów mających wspólny typ:
li = ['A0','c5','A8','A2','A5','c2','A3','A9']
print sum(1 for el in li if el[0]=='A' and el[1] in '01234')
Daje
3
, Nie 6
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-14 15:51:59
Chociaż to bardzo stare pytanie, ale ponieważ nie znalazłem jednego linera, zrobiłem jeden.
# original numbers in list
l = [1, 2, 2, 3, 3, 3, 4]
# empty dictionary to hold pair of number and its count
d = {}
# loop through all elements and store count
[ d.update( {i:d.get(i, 0)+1} ) for i in l ]
print(d)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-07-04 06:20:40
Możesz również użyć countOf
metoda wbudowanego modułu operator
.
>>> import operator
>>> operator.countOf([1, 2, 3, 4, 1, 4, 1], 1)
3
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-18 20:08:11
Podano listę X
import numpy as np
X = [1, -1, 1, -1, 1]
Słownik pokazujący i: częstotliwość(i) dla elementów tej listy to:
{i:X.count(i) for i in np.unique(X)}
Wyjście:
{-1: 2, 1: 3}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-09-19 01:08:42
Może nie być najbardziej wydajny, wymaga dodatkowego przejścia do usuwania duplikatów.
Implementacja funkcjonalna:
arr = np.array(['a','a','b','b','b','c'])
print(set(map(lambda x : (x , list(arr).count(x)) , arr)))
Zwraca:
{('c', 1), ('b', 3), ('a', 2)}
Lub return as dict
:
print(dict(map(lambda x : (x , list(arr).count(x)) , arr)))
Zwraca:
{'b': 3, 'c': 1, 'a': 2}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-01 10:38:08
Użyłbym filter()
, weźmy przykład Łukasza:
>>> lst = [1, 2, 3, 4, 1, 4, 1]
>>> len(filter(lambda x: x==1, lst))
3
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-28 19:09:48
sum([1 for elem in <yourlist> if elem==<your_value>])
Zwróci ilość wystąpień Twojej wartości
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-23 01:20:52
Jeśli chcesz mieć liczbę wystąpień dla danego elementu:
>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> single_occurrences = Counter(z)
>>> print(single_occurrences.get("blue"))
3
>>> print(single_occurrences.values())
dict_values([3, 2, 1])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-29 14:05:39
l2=[1,"feto",["feto",1,["feto"]],['feto',[1,2,3,['feto']]]]
count=0
def Test(l):
global count
if len(l)==0:
return count
count=l.count("feto")
for i in l:
if type(i) is list:
count+=Test(i)
return count
print(Test(l2))
Spowoduje to rekurencyjne zliczanie lub Wyszukiwanie pozycji na liście, nawet jeśli znajduje się ona w list of lists
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-20 04:54:12
Użyj %timeit, aby sprawdzić, która operacja jest bardziej wydajna. np.operacje zliczania tablic powinny być szybsze.
from collections import Counter
mylist = [1,7,7,7,3,9,9,9,7,9,10,0]
types_counts=Counter(mylist)
print(types_counts)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-31 15:03:35
def countfrequncyinarray(arr1):
r=len(arr1)
return {i:arr1.count(i) for i in range(1,r+1)}
arr1=[4,4,4,4]
a=countfrequncyinarray(arr1)
print(a)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-07 08:29:21