📜  在Python中有效地使用迭代

📅  最后修改于: 2022-05-13 01:54:38.535000             🧑  作者: Mango

在Python中有效地使用迭代

先决条件: Python中的迭代器 以下是使用迭代器的不同方法。 C 风格的方法:这种方法需要事先了解总迭代次数。

Python
# A C-style way of accessing list elements
cars = ["Aston", "Audi", "McLaren"]
i = 0
while (i < len(cars)):
    print cars[i]
    i += 1


Python
# Accessing items using for-in loop
 
cars = ["Aston", "Audi", "McLaren"]
for x in cars:
    print x


Python
# Accessing items using indexes and for-in
 
cars = ["Aston", "Audi", "McLaren"]
for i in range(len(cars)):
    print cars[i]


Python
# Accessing items using enumerate()
 
cars = ["Aston" , "Audi", "McLaren "]
for i, x in enumerate(cars):
    print (x)


Python
# Accessing items and indexes enumerate()
 
cars = ["Aston" , "Audi", "McLaren "]
for x in enumerate(cars):
    print (x[0], x[1])


Python
# Printing return value of enumerate()
 
cars = ["Aston" , "Audi", "McLaren "]
print enumerate(cars)


Python
# demonstrating the use of start in enumerate
 
cars = ["Aston" , "Audi", "McLaren "]
for x in enumerate(cars, start=1):
    print (x[0], x[1])


Python
# Two separate lists
cars = ["Aston", "Audi", "McLaren"]
accessories = ["GPS kit", "Car repair-tool kit"]
 
# Single dictionary holds prices of cars and
# its accessories.
# First three items store prices of cars and
# next two items store prices of accessories.
prices = {1:"570000$", 2:"68000$", 3:"450000$",
          4:"8900$", 5:"4500$"}
 
# Printing prices of cars
for index, c in enumerate(cars, start=1):
    print "Car: %s Price: %s"%(c, prices[index])
 
# Printing prices of accessories
for index, a in enumerate(accessories,start=1):
    print ("Accessory: %s Price: %s"\
           %(a,prices[index+len(cars)]))


Python
# Python program to demonstrate the working of zip
 
# Two separate lists
cars = ["Aston", "Audi", "McLaren"]
accessories = ["GPS", "Car Repair Kit",
               "Dolby sound kit"]
 
# Combining lists and printing
for c, a in zip(cars, accessories):
    print "Car: %s, Accessory required: %s"\
          %(c, a)


Python
# Python program to demonstrate unzip (reverse
# of zip)using * with zip function
 
# Unzip lists
l1,l2 = zip(*[('Aston', 'GPS'),
              ('Audi', 'Car Repair'),
              ('McLaren', 'Dolby sound kit')
           ])
 
# Printing unzipped lists     
print(l1)
print(l2)


输出:

Aston
Audi 
McLaren 

要点:

  • Python程序员很少使用这种循环方式。
  • 这种 4 步方法不会产生单视图循环结构的紧凑性。
  • 这在大型程序或设计中也容易出错。
  • Python中没有 C 风格的 for 循环,即像 for (int i=0; i

使用 for-in(或for each )样式:此样式用于包含列表、字典、n 维数组等迭代器的Python 。迭代器在循环时获取每个组件并打印数据。迭代器在此构造中自动递增/递减。

Python

# Accessing items using for-in loop
 
cars = ["Aston", "Audi", "McLaren"]
for x in cars:
    print x

输出:

Aston
Audi 
McLaren 

有关不同数据类型的更多示例,请参阅此内容。使用 Range函数进行索引:我们也可以在Python中使用 range() 进行索引。

Python

# Accessing items using indexes and for-in
 
cars = ["Aston", "Audi", "McLaren"]
for i in range(len(cars)):
    print cars[i]

输出:

Aston
Audi 
McLaren 

枚举:枚举是内置的Python函数,它将输入作为迭代器、列表等,并返回一个元组,其中包含迭代器序列中该索引处的索引和数据。例如,enumerate(cars),返回一个迭代器,它将返回 (0, cars[0]), (1, cars[1]), (2, cars[2]) 等等。

Python

# Accessing items using enumerate()
 
cars = ["Aston" , "Audi", "McLaren "]
for i, x in enumerate(cars):
    print (x)

输出 :

Aston
Audi
McLaren 

下面的解决方案也有效。

Python

# Accessing items and indexes enumerate()
 
cars = ["Aston" , "Audi", "McLaren "]
for x in enumerate(cars):
    print (x[0], x[1])

输出 :

(0, 'Aston')
(1, 'Audi')
(2, 'McLaren ')

我们也可以直接打印 enumerate() 的返回值,看看它返回了什么。

Python

# Printing return value of enumerate()
 
cars = ["Aston" , "Audi", "McLaren "]
print enumerate(cars)

输出 :

[(0, 'Aston'), (1, 'Audi'), (2, 'McLaren ')]

Enumerate 采用默认设置为零的参数 start。我们可以将此参数更改为我们喜欢的任何值。在下面的代码中,我们使用 start 作为 1。

Python

# demonstrating the use of start in enumerate
 
cars = ["Aston" , "Audi", "McLaren "]
for x in enumerate(cars, start=1):
    print (x[0], x[1])

输出 :

(1, 'Aston')
(2, 'Audi')
(3, 'McLaren ')

enumerate() 有助于嵌入解决方案以访问迭代器中的每个数据项并获取每个数据项的索引。

循环扩展: i)单个循环构造的两个迭代器:在这种情况下,列表和字典将用于使用 enumerate函数的单个循环块中的每次迭代。让我们看看例子。

Python

# Two separate lists
cars = ["Aston", "Audi", "McLaren"]
accessories = ["GPS kit", "Car repair-tool kit"]
 
# Single dictionary holds prices of cars and
# its accessories.
# First three items store prices of cars and
# next two items store prices of accessories.
prices = {1:"570000$", 2:"68000$", 3:"450000$",
          4:"8900$", 5:"4500$"}
 
# Printing prices of cars
for index, c in enumerate(cars, start=1):
    print "Car: %s Price: %s"%(c, prices[index])
 
# Printing prices of accessories
for index, a in enumerate(accessories,start=1):
    print ("Accessory: %s Price: %s"\
           %(a,prices[index+len(cars)]))

输出:

Car: Aston Price: 570000$
Car: Audi Price: 68000$
Car: McLaren Price: 450000$
Accessory: GPS kit Price: 8900$
Accessory: Car repair-tool kit Price: 4500$

ii) zip函数(两个迭代器都用于单循环结构):该函数有助于在第 i 个位置组合相似类型的迭代器(list-list 或 dict-dict 等)数据项。它使用这些输入迭代器中最短的长度。其他较大长度的迭代器项将被跳过。如果迭代器为空,则返回 No output。

例如,对两个列表(迭代器)使用 zip 有助于组合单个汽车及其所需的附件。

Python

# Python program to demonstrate the working of zip
 
# Two separate lists
cars = ["Aston", "Audi", "McLaren"]
accessories = ["GPS", "Car Repair Kit",
               "Dolby sound kit"]
 
# Combining lists and printing
for c, a in zip(cars, accessories):
    print "Car: %s, Accessory required: %s"\
          %(c, a)

输出:

Car: Aston, Accessory required: GPS
Car: Audi, Accessory required: Car Repair Kit
Car: McLaren, Accessory required: Dolby sound kit

这些与 zip函数相反的迭代器称为使用“*”运算符解压缩。使用 enumerate函数和 zip函数有助于实现对Python中迭代逻辑的有效扩展,并解决大量任务或问题的更多子问题。

Python

# Python program to demonstrate unzip (reverse
# of zip)using * with zip function
 
# Unzip lists
l1,l2 = zip(*[('Aston', 'GPS'),
              ('Audi', 'Car Repair'),
              ('McLaren', 'Dolby sound kit')
           ])
 
# Printing unzipped lists     
print(l1)
print(l2)

输出:

('Aston', 'Audi', 'McLaren')
('GPS', 'Car Repair', 'Dolby sound kit')