“Coleções.Counter (String) .Mem_Common” Respostas de código

Coleções.Counter (String) .Mem_Common


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

Coleções.Counter (String) .Mem_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

Coleções.Counter (String) .Mem_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

Coleções.Counter (String) .Mem_Common


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

Coleções.Counter (String) .Mem_Common


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

Coleções.Counter (String) .Mem_Common


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

Procure respostas de código populares por idioma

Procurar outros idiomas de código