📜  Python中的循环技术

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

Python中的循环技术

Python在各种顺序容器中通过某些内置函数支持各种循环技术。这些方法主要在竞争性编程中非常有用,在各种需要特定技术的项目中也非常有用,这些项目需要使用循环来维护代码的整体结构。由于不需要声明我们在传统循环方法中声明的额外变量,因此节省了大量时间和内存空间。

它们在哪里使用?

不同的循环技术主要用于我们不需要实际操作整个容器的结构和顺序的地方,而只是打印一次性实例的元素,容器中不会发生就地更改。这也可以在实例中使用以节省时间。

使用Python数据结构的不同循环技术是:

  • 使用 enumerate(): enumerate() 用于循环打印索引号以及该特定索引中存在的值的容器。
Python3
# python code to demonstrate working of enumerate()
 
for key, value in enumerate(['The', 'Big', 'Bang', 'Theory']):
    print(key, value)


Python3
# python code to demonstrate working of enumerate()
 
for key, value in enumerate(['Geeks', 'for', 'Geeks',
                             'is', 'the', 'Best',
                             'Coding', 'Platform']):
    print(value, end=' ')


Python3
# python code to demonstrate working of zip()
 
# initializing list
questions = ['name', 'colour', 'shape']
answers = ['apple', 'red', 'a circle']
 
# using zip() to combine two containers
# and print values
for question, answer in zip(questions, answers):
    print('What is your {0}?  I am {1}.'.format(question, answer))


Python3
# python code to demonstrate working of items()
 
d = {"geeks": "for", "only": "geeks"}
 
# iteritems() is renamed to items() in python3
# using items to print the dictionary key-value pair
print("The key value pair using items is : ")
for i, j in d.items():
    print(i, j)


Python3
# python code to demonstrate working of items()
 
king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya',
        'Modi': 'The Changer'}
 
# using items to print the dictionary key-value pair
for key, value in king.items():
    print(key, value)


Python3
# python code to demonstrate working of sorted()
 
# initializing list
lis = [1, 3, 5, 6, 2, 1, 3]
 
# using sorted() to print the list in sorted order
print("The list in sorted order is : ")
for i in sorted(lis):
    print(i, end=" ")
 
print("\r")
 
# using sorted() and set() to print the list in sorted order
# use of set() removes duplicates.
print("The list in sorted order (without duplicates) is : ")
for i in sorted(set(lis)):
    print(i, end=" ")


Python3
# python code to demonstrate working of sorted()
 
# initializing list
basket = ['guave', 'orange', 'apple', 'pear',
          'guava', 'banana', 'grape']
 
# using sorted() and set() to print the list
#  in sorted order
for fruit in sorted(set(basket)):
    print(fruit)


Python3
# python code to demonstrate working of reversed()
 
# initializing list
lis = [1, 3, 5, 6, 2, 1, 3]
 
 
# using reversed() to print the list in reversed order
print("The list in reversed order is : ")
for i in reversed(lis):
    print(i, end=" ")


Python3
# python code to demonstrate working of reversed()
 
# using reversed() to print in reverse order
for i in reversed(range(1, 10, 3)):
    print(i)


输出:

0 The
1 Big
2 Bang
3 Theory

Python3

# python code to demonstrate working of enumerate()
 
for key, value in enumerate(['Geeks', 'for', 'Geeks',
                             'is', 'the', 'Best',
                             'Coding', 'Platform']):
    print(value, end=' ')

输出:

Geeks for Geeks is the Best Coding Platform 
  • 使用 zip(): zip() 用于组合 2 个相似的容器(list-list 或 dict-dict)按顺序打印值。循环只存在到较小的容器结束。 zip() 和 enumerate() 的详细解释可以在这里找到。

Python3

# python code to demonstrate working of zip()
 
# initializing list
questions = ['name', 'colour', 'shape']
answers = ['apple', 'red', 'a circle']
 
# using zip() to combine two containers
# and print values
for question, answer in zip(questions, answers):
    print('What is your {0}?  I am {1}.'.format(question, answer))

输出:

What is your name?  I am apple.
What is your color?  I am red.
What is your shape?  I am a circle.
  • 使用 iteritem(): iteritems() 用于遍历字典,按顺序打印字典键值对,在Python 3 版本之前使用。
  • 使用 items(): items() 在字典上执行与 iteritems() 类似的任务,但与 iteritems() 相比有一定的缺点。
    • 非常耗时。在大型词典上调用它会消耗大量时间。
    • 它需要大量的内存。有时在字典上调用时会占用双倍的内存。

示例 1:

Python3

# python code to demonstrate working of items()
 
d = {"geeks": "for", "only": "geeks"}
 
# iteritems() is renamed to items() in python3
# using items to print the dictionary key-value pair
print("The key value pair using items is : ")
for i, j in d.items():
    print(i, j)

输出:

The key value pair using iteritems is : 
geeks for
only geeks
The key value pair using items is : 
geeks for
only geeks

示例 2:

Python3

# python code to demonstrate working of items()
 
king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya',
        'Modi': 'The Changer'}
 
# using items to print the dictionary key-value pair
for key, value in king.items():
    print(key, value)

输出:

Akbar The Great
Chandragupta The Maurya
Modi The Changer
  • 使用 sorted(): sorted() 用于打印容器是否已排序。它不对容器进行排序,而只是按 1 个实例的排序顺序打印容器。可以结合使用 set() 来删除重复的事件。

示例 1:

Python3

# python code to demonstrate working of sorted()
 
# initializing list
lis = [1, 3, 5, 6, 2, 1, 3]
 
# using sorted() to print the list in sorted order
print("The list in sorted order is : ")
for i in sorted(lis):
    print(i, end=" ")
 
print("\r")
 
# using sorted() and set() to print the list in sorted order
# use of set() removes duplicates.
print("The list in sorted order (without duplicates) is : ")
for i in sorted(set(lis)):
    print(i, end=" ")

输出:

The list in sorted order is : 
1 1 2 3 3 5 6 
The list in sorted order (without duplicates) is : 
1 2 3 5 6 

示例 2:

Python3

# python code to demonstrate working of sorted()
 
# initializing list
basket = ['guave', 'orange', 'apple', 'pear',
          'guava', 'banana', 'grape']
 
# using sorted() and set() to print the list
#  in sorted order
for fruit in sorted(set(basket)):
    print(fruit)

输出:

apple
banana
grape
guava
guave
orange
pear
  • 使用 reversed(): reversed() 用于打印 容器以相反的顺序。它不反映对原始列表的任何更改

示例 1:

Python3

# python code to demonstrate working of reversed()
 
# initializing list
lis = [1, 3, 5, 6, 2, 1, 3]
 
 
# using reversed() to print the list in reversed order
print("The list in reversed order is : ")
for i in reversed(lis):
    print(i, end=" ")

输出:

The list in reversed order is : 
3 1 2 6 5 3 1 

示例 2:

Python3

# python code to demonstrate working of reversed()
 
# using reversed() to print in reverse order
for i in reversed(range(1, 10, 3)):
    print(i)

输出:

7
4
1
  • 这些技术可以快速使用并减少编码工作。 for、while 循环需要改变容器的整个结构。
  • 这些循环技术不需要对容器进行任何结构更改。他们有关键字来表达使用的确切目的。然而,for、while 循环不能做出任何预先预测或猜测,即不容易一眼就理解其目的。
  • 循环技术使代码比使用 for & while 循环更简洁。