zip()

Contents
Введение
Пример
Похожие статьи

Введение

Функция zip() возвращает кортеж

Синтаксис

zip(iterable)

Пример

Убедимся, что zip() выдаёт (yields) кортежи

# temparature sunday = [12, 14, 15, 15, 17, 21, 22, 22, 23, 22, 20, 18] monday = [13, 14, 14, 14, 16, 20, 21, 22, 22, 21, 19, 17] for item in zip(sunday, monday): print(item) ~

python zip_ex.py

(12, 13) (14, 14) (15, 14) (15, 14) (17, 16) (21, 20) (22, 21) (22, 22) (23, 22) (22, 21) (20, 19) (18, 17)

У объекта класса zip есть методы __iter__ и __next__

z = zip(sunday, monday) print(type(z)) print(dir(z)) print(next(z)) print(next(z))

<class 'zip'> ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] (12, 13) (14, 14)

for sun, mon in zip(sunday, monday): print("average =", (sun + mon) / 2)

average = 12.5 average = 14.0 average = 14.5 average = 14.5 average = 16.5 average = 20.5 average = 21.5 average = 22.0 average = 22.5 average = 21.5 average = 19.5 average = 17.5

Добавим ещё один день недели

tuesday = [2, 2, 3, 7, 9, 10, 11, 12, 10, 9, 8, 8] for temps in zip(sunday, monday, tuesday): print( f"min = {min(temps):4.1f}, max={max(temps):4.1f}," f"average={sum(temps) / len(temps):4.1f}")

min = 2.0, max=13.0,average= 9.0 min = 2.0, max=14.0,average=10.0 min = 3.0, max=15.0,average=10.7 min = 7.0, max=15.0,average=12.0 min = 9.0, max=17.0,average=14.0 min = 10.0, max=21.0,average=17.0 min = 11.0, max=22.0,average=18.0 min = 12.0, max=22.0,average=18.7 min = 10.0, max=23.0,average=18.3 min = 9.0, max=22.0,average=17.3 min = 8.0, max=20.0,average=15.7 min = 8.0, max=18.0,average=14.3

С помощью itertools chain можно перебрать элементы всех трёх списков без конкатенации

from itertools import chain temperatures = chain(sunday, monday, tuesday) print(all(t > 0 for t in temperatures))

True

Related Articles
*args **kwargs
Лямбда функции
all()
any()
map()
zip()
sorted()
Функции первого класса
Замыкания
Декораторы
Кэширование
Python
if, elif, else
Циклы
Методы
enum

Search on this site

Subscribe to @aofeed channel for updates

Visit Channel

@aofeed

Feedbak and Questions in Telegram

@aofeedchat