在字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来:
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
结果输出:
gallahad the pure
robin the brave
在序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到:
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
结果输出:
0 tic
1 tac
2 toe
同时遍历两个或更多的序列,可以使用 zip() 组合:
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
结果输出:
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
要反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数:
for i in reversed(range(1, 10, 2)):
print(i)
结果输出:
D:\PycharmProjects\TestPython\venv\Scripts\python.exe D:/PycharmProjects/TestPython/TestMain.py
9
7
5
3
1
要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值:
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
结果输出:
D:\PycharmProjects\TestPython\venv\Scripts\python.exe D:/PycharmProjects/TestPython/TestMain.py
apple
banana
orange
pear
遍历范围内指定的素数。
#!/usr/bin/python3
# 输出指定范围内的素数
# take input from the user
lower = int(input("输入区间最小值: "))
upper = int(input("输入区间最大值: "))
for num in range(lower, upper + 1):
# 素数大于 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
结果输出:
输入区间最小值: 1
输入区间最大值: 34
2
3
5
7
11
13
17
19
23
29
31
演示乘法口诀 九九乘法表
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.runoob.com
# 九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print('{}x{}={}\t\t'.format(j, i, i * j), end='')#\t 横向制表符
print()
结果输出:
1x1=1
1x2=2 2x2=4
1x3=3 2x3=6 3x3=9
1x4=4 2x4=8 3x4=12 4x4=16
1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81