“collections.counter (string) .most_common” Kode Jawaban

collections.counter (string) .most_common


# getting count
counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
countDog = counter['Dog']
print(countDog)  # 2
Fantastic Frog

collections.counter (string) .most_common


counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
# setting count
counter['Horse'] = 0
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})

# setting count for non-existing key, adds to Counter
counter['Unicorn'] = 1
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Unicorn': 1, 'Horse': 0})
Fantastic Frog

collections.counter (string) .most_common


counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})

# elements()
elements = counter.elements()  # doesn't return elements with count 0 or less
for value in elements:
    print(value)
Fantastic Frog

collections.counter (string) .most_common


# Counter works with non-numbers too
special_counter = Counter(name='Pankaj', age=20)
print(special_counter)  # Counter({'name': 'Pankaj', 'age': 20})
Fantastic Frog

collections.counter (string) .most_common


# getting count for non existing key, don't cause KeyError
print(counter['Unicorn'])  # 0
Fantastic Frog

collections.counter (string) .most_common


# Delete element from Counter
del counter['Unicorn']
print(counter)  # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})
Fantastic Frog

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya