程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Learn the zip() function in Python

編輯:Python

Python中的zip()A function is a neat little function,It accepts two or more sequences as input,and allows you to iterate over these sequences simultaneously.To illustrate how to use it in your programzip(),We'll take a look at that in this tutorialzip()的幾個例子.When we say iterate over variables,我們指的是 Python Various iteration variables in ,如列表、元組、字符串等.現在讓我們從 zip() Some examples of functions to start.


zip() 示例一

meats = ['Steak', 'Pork', 'Duck', 'Turkey']
toppings = ['Butter', 'Garlic', 'Olive Oil', 'Cranberry']
for meat, topping in zip(meats, toppings):
print(f'{meat} topped with {topping}')
復制代碼
Steak topped with Butter
Pork topped with Garlic
Duck topped with Olive Oil
Turkey topped with Cranberry
復制代碼

zip() 實例二

numbers = [1, 2, 3, 4]
str_numbers = ['One', 'Two', 'Three', 'Four']
result = zip(numbers, str_numbers)
print(result)
print(list(result))
復制代碼
[(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four')]
復制代碼

帶字典的 zip()

colors = ['Red', 'White', 'Blue']
cars = ['Corvette', 'Bronco', 'Mustang']
my_dict = {}
for color, car in zip(colors, cars):
my_dict[color] = car
print(my_dict)
復制代碼
{'Red': 'Corvette', 'White': 'Bronco', 'Blue': 'Mustang'}
復制代碼

Calls without an iterablezip().

result = zip()
print(result)
復制代碼
<zip object at 0x0000025021AD51C0>
復制代碼

向zip()Pass more than two iterable objects

numerals = [1, 2, 3]
str_numerals = ['One', 'Two', 'Three']
roman_numerals = ['I', 'II', 'III']
result = zip(numerals, str_numerals, roman_numerals)
print(list(result))
復制代碼
[(1, 'One', 'I'), (2, 'Two', 'II'), (3, 'Three', 'III')]
復制代碼

將zipThe object is turned into a list of primitives

states = ['Massachusetts', 'Colorado', 'California', 'Florida']
capitals = ['Boston', 'Denver', 'Sacremento', 'Tallahassee']
zipped = zip(states, capitals)
ziplist = list(zipped)
print(ziplist)
復制代碼
[('Massachusetts', 'Boston'), ('Colorado', 'Denver'), ('California', 'Sacremento'), ('Florida', 'Tallahassee')]
復制代碼

將zip對象轉換為一個字典

states = ['Massachusetts', 'Colorado', 'California', 'Florida']
capitals = ['Boston', 'Denver', 'Sacremento', 'Tallahassee']
zipped = zip(states, capitals)
zipdict = dict(zipped)
print(zipdict)
復制代碼
{'Massachusetts': 'Boston', 'Colorado': 'Denver', 'California': 'Sacremento', 'Florida': 'Tallahassee'}
復制代碼

在Python next()函數中使用zip()

states = ['Massachusetts', 'Colorado', 'California', 'Florida']
capitals = ['Boston', 'Denver', 'Sacremento', 'Tallahassee']
zipped = zip(states, capitals)
while True:
try:
tup = next(zipped)
print(tup[0], "capital is", tup[1])
except StopIteration:
break
復制代碼
Massachusetts capital is Boston
Colorado capital is Denver
California capital is Sacremento
Florida capital is Tallahassee
復制代碼

How to decompress a compressed object

states = ['Massachusetts', 'Colorado', 'California', 'Florida']
capitals = ['Boston', 'Denver', 'Sacremento', 'Tallahassee']
zipped = zip(states, capitals)
print(zipped)
first, second = zip(*zipped)
print(first)
print(second)
復制代碼
<zip object at 0x000001A6ED61E1C0>
('Massachusetts', 'Colorado', 'California', 'Florida')
('Boston', 'Denver', 'Sacremento', 'Tallahassee')
復制代碼

iteration variables of different lengths

到目前為止,All the examples we've looked at use an iterative table with the same number of elements.Use when you try to iterate over one of the objects longer than the other zip() 函數時會發生什麼?Python The default behavior of is to limit operations to smaller-sized iteration tables.這裡是一個例子,An iterative table has 3 個元素,另一個有 5 個元素.

one = [1, 2, 3, 4, 5]
two = ['a', 'b', 'c']
result = zip(one, two)
print(list(result))
復制代碼
[(1, 'a'), (2, 'b'), (3, 'c')]
復制代碼

如果你想改變行為,in order to use longer iterators,你可以使用 zip_longest() 函數,這是 itertools 包的一部分.

import itertools as it
one = [1, 2, 3, 4, 5]
two = ['a', 'b', 'c']
result = it.zip_longest(one, two)
print(list(result))
復制代碼
[(1, 'a'), (2, 'b'), (3, 'c'), (4, None), (5, None)]
復制代碼

你可以看到,zip_longest()The function just inserts one for those slots that have nulls due to different sizes of iteration tablesNone值.If you want to specify a different value,You can take advantage of it like thisfillvalue參數.

import itertools as it
one = [1, 2, 3, 4, 5]
two = ['a', 'b', 'c']
result = it.zip_longest(one, two, fillvalue='')
print(list(result))
復制代碼
[(1, 'a'), (2, 'b'), (3, 'c'), (4, ''), (5, '')]
復制代碼

Python zip() 函數總結

zip()The function receives the iteration variable,Aggregate them into a tuple and return it.

zip()函數的語法是:

zip(*iterables)

參數iterables可以是內置的iterables,如list、string、dict,或者用戶定義的iterables.

zip()The function returns an iterable of primitives based on an iterable object.

  • 如果我們不傳遞任何參數,zip()返回一個空的迭代器

  • If passed in an iterable object,zip()Returns an iterator of primitives,There is only one element per primitive.

  • If multiple iterators are passed,zip()Returns an iterator of primitives,Each primitive contains the elements of all iterators.

    假設,Two iterators are passed tozip();An iterator contains three elements,The other contains five elements.那麼,The returned iterator will contain three primitives.This is because when the shortest iterator is used up,迭代器就會停止.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved