“collecess.counter (String) .most_common” Code-Antworten

collecess.counter (String) .most_common


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

collecess.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

collecess.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

collecess.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

collecess.counter (String) .most_common


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

collecess.counter (String) .most_common


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

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen