python之遍历技巧

字典遍历:关键字和对应的值可以使用 items() 方法同时解读出来;

eg:

knights = {'gallahad': 'the pure', 'robin': 'the brave'}

for k, v in knights.items():

    print(k, v)

gallahad the pure
robin the brave

序列遍历:索引位置和对应值可以使用 enumerate() 函数同时得到;

eg:

for i,v in enumerate([i for i in range(2,5)]):

    print(i,v)

0 2
1 3
2 4

同时遍历两个或更多的序列,可以使用 zip() 组合;

eg:

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() 函数;

eg:

for i in reversed(range(1, 10, 2)):

    print(i)

9
7
5
3
1

要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值:

eg:

basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']

for f in sorted(set(basket)):

     print(f)

apple
banana
orange
pear

str():把字典、元组、列表转换为字符串;

扫描二维码关注公众号,回复: 15446376 查看本文章

eval():字符串转换为字典、元组、列表

1、简单表达式
 
 
print(eval('1+2'))
 
 
输出结果:3
 
 
2、字符串转字典
 
 
print(eval("{'name':'linux','age':18}")
 
 
输出结果:{'name':'linux','age':18}
 
 
3、传递全局变量
 
 
print(eval("{'name':'linux','age':age}",{"age":1822}))
 
 
输出结果:{'name': 'linux', 'age': 1822}
 
 
4、传递本地变量
 
 
age=18
 
 
print(eval("{'name':'linux','age':age}",{"age":1822},locals()))
 
 
输出结果:{'name': 'linux', 'age': 18}

zip函数for循环使用:

for循环里zip()函数用来并行遍历列表,输出数据
A = ['python','java','c++','abc']
B = ['a','b','c','d']
for i,j in zip(A,B):
    print(i,j)

enumerate()函数:

 for循环里enumerate()函数是一个枚举函数,用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。

A = ['python','java','c++','abc']
for i,val in enumerate(A):
    print(i,val)

猜你喜欢

转载自blog.csdn.net/Darin2017/article/details/121628846