Python-基础知识学习之内建序列函数(enumerate、sorted、zip、reversed)

1、enumerate经常用于遍历,可以对列表遍历之后得到一个带索引和值的元组,这样不需要外部再加参数去记录索引了:

alist = [3, 2, 4, 6, 8, 9, 1]
for tup in enumerate(alist):
    print(tup)

#打印
    (0, 3)  (1, 2)  (2, 4) (3, 6) (4, 8) (5, 9) (6, 1)


#另一个用法
alist = ['foo', 'bar', 'eye']
mapping = {}
for i,v in enumerate(alist):
    mapping[v] = i

print(mapping)
#打印
    {'bar': 1, 'eye': 2, 'foo': 0}

2、sorted函数可以返回一个根据任意序列中的元素新建已排序列表:

alist = [7, 1, 2, 6, 0, 3, 2]
blist = sorted(alist)
print(blist)
#打印
    [0, 1, 2, 3, 6, 7]

blist = sorted('hello world')
print(blist)
#打印
    [' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

3、zip函数是将列表、元组或其他序列的元素配对,新建一个元组构成的列表:

alist = ['hello', 'world', 'code']
blist = ['year', 'month', 'day']
zipped = zip(alist, blist)
clist = list(zipped)
print(clist)
#打印
    [('hello', 'year'), ('world', 'month'), ('code', 'day')]

zip可以处理任意长度的序列,但是长度由最短的序列决定:

#接上面代码
dlist = [False, True]
clist = list(zip(alist, blist, dlist))
print(clist)
#打印
    [('hello', 'year', False), ('world', 'month', True)]



#通过zip可以同时遍历多个序列,并且和enumerate同时使用:
for i,(a,b) in enumerate(zip(alist, blist)):
    print('{0}: {1}, {2}'.format(i, a, b))
#打印
    0: hello, year
    1: world, month
    2: code, day



#如果有已经配对好的序列,也可以通过zip去拆分:
alist = [('hello', 'world'), ('year', 'month'), ('one', 'two')]
first, last = zip(*alist)
print(first)
#打印
    ('hello', 'year', 'one')

print(last)
#打印
    ('world', 'month', 'two')

4、reversed函数将序列的元素倒序排序:

alist = list(range(10))
blist = list(reversed(alist))
print(blist)
#打印
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

 

你可能感兴趣的:(Python,Python学习记录)