PYTHON_JOB_INTERVIEW Telegram 1205
This media is not supported in your browser
VIEW IN TELEGRAM
Python-трюк: быстрая группировка данных

Хотите сгруппировать элементы по ключу без лишних циклов?
Используйте itertools.groupby — но не забудьте предварительно отсортировать данные по этому ключу, иначе группы будут неправильными.


from itertools import groupby
from operator import itemgetter

data = [
{"user": "alice", "score": 8},
{"user": "bob", "score": 5},
{"user": "alice", "score": 7},
{"user": "bob", "score": 9},
]

# Сортируем по ключу
data.sort(key=itemgetter("user"))

# Группируем и считаем средний балл
for user, items in groupby(data, key=itemgetter("user")):
scores = [i["score"] for i in items]
print(user, "avg score:", sum(scores) / len(scores))



#Python #itertools #groupby #lifehack
👍87🔥3



tgoop.com/python_job_interview/1205
Create:
Last Update:

Python-трюк: быстрая группировка данных

Хотите сгруппировать элементы по ключу без лишних циклов?
Используйте itertools.groupby — но не забудьте предварительно отсортировать данные по этому ключу, иначе группы будут неправильными.


from itertools import groupby
from operator import itemgetter

data = [
{"user": "alice", "score": 8},
{"user": "bob", "score": 5},
{"user": "alice", "score": 7},
{"user": "bob", "score": 9},
]

# Сортируем по ключу
data.sort(key=itemgetter("user"))

# Группируем и считаем средний балл
for user, items in groupby(data, key=itemgetter("user")):
scores = [i["score"] for i in items]
print(user, "avg score:", sum(scores) / len(scores))



#Python #itertools #groupby #lifehack

BY Python вопросы с собеседований


Share with your friend now:
tgoop.com/python_job_interview/1205

View MORE
Open in Telegram


Telegram News

Date: |

Deputy District Judge Peter Hui sentenced computer technician Ng Man-ho on Thursday, a month after the 27-year-old, who ran a Telegram group called SUCK Channel, was found guilty of seven charges of conspiring to incite others to commit illegal acts during the 2019 extradition bill protests and subsequent months. In handing down the sentence yesterday, deputy judge Peter Hui Shiu-keung of the district court said that even if Ng did not post the messages, he cannot shirk responsibility as the owner and administrator of such a big group for allowing these messages that incite illegal behaviors to exist. The court said the defendant had also incited people to commit public nuisance, with messages calling on them to take part in rallies and demonstrations including at Hong Kong International Airport, to block roads and to paralyse the public transportation system. Various forms of protest promoted on the messaging platform included general strikes, lunchtime protests and silent sit-ins. How to Create a Private or Public Channel on Telegram? Add up to 50 administrators
from us


Telegram Python вопросы с собеседований
FROM American