Telegram Group & Telegram Channel
Что выведет этот код?

Могло показаться, что выведется словарь с буквами и их повторением в словаре.

dict.setdefault(key, default=None) - возвращает значение по ключу key, а если ключа нет в словаре, то добавляет пару key=default и возвращает значение default.

dict.get(key, default=None) - возвращает значение по ключу key, а если ключа нет, то возвращает default не добавляя пару в словарь.

То есть мы просто каждой букве в слове поставили значение counter.get(char, 1) + 1 = 2.

Чтобы посчитать реальный счетчик повторении есть несколько способов:


s = "hello"

# 1
counter = {}
for char in s:
counter[char] = counter.setdefault(char, 0) + 1

# 2
counter = {}
for char in s:
counter[char] = counter.get(char, 0) + 1

# 3
from collections import defaultdict
counter = defaultdict(int)
for char in s:
counter[char] += 1

# 4
from collections import Counter
counter = Counter(s)


#dict #counter



tg-me.com/pythrone/13
Create:
Last Update:

Что выведет этот код?

Могло показаться, что выведется словарь с буквами и их повторением в словаре.

dict.setdefault(key, default=None) - возвращает значение по ключу key, а если ключа нет в словаре, то добавляет пару key=default и возвращает значение default.

dict.get(key, default=None) - возвращает значение по ключу key, а если ключа нет, то возвращает default не добавляя пару в словарь.

То есть мы просто каждой букве в слове поставили значение counter.get(char, 1) + 1 = 2.

Чтобы посчитать реальный счетчик повторении есть несколько способов:


s = "hello"

# 1
counter = {}
for char in s:
counter[char] = counter.setdefault(char, 0) + 1

# 2
counter = {}
for char in s:
counter[char] = counter.get(char, 0) + 1

# 3
from collections import defaultdict
counter = defaultdict(int)
for char in s:
counter[char] += 1

# 4
from collections import Counter
counter = Counter(s)


#dict #counter

BY PyThrone




Share with your friend now:
tg-me.com/pythrone/13

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

Telegram announces Search Filters

With the help of the Search Filters option, users can now filter search results by type. They can do that by using the new tabs: Media, Links, Files and others. Searches can be done based on the particular time period like by typing in the date or even “Yesterday”. If users type in the name of a person, group, channel or bot, an extra filter will be applied to the searches.

For some time, Mr. Durov and a few dozen staffers had no fixed headquarters, but rather traveled the world, setting up shop in one city after another, he told the Journal in 2016. The company now has its operational base in Dubai, though it says it doesn’t keep servers there.Mr. Durov maintains a yearslong friendship from his VK days with actor and tech investor Jared Leto, with whom he shares an ascetic lifestyle that eschews meat and alcohol.

telegram from hk


Telegram PyThrone
FROM USA