Python- learning knowledge base built-in sequence function (enumerate, sorted, zip, reversed)

1, enumerate often used to traverse, it can be indexed and a tuple of values ​​after traversal list, so does not require additional external parameters to record the index:

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 new function can return a ranked list of elements according to any of the sequences:

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 list function is a pair of elements, or other sequences of tuples, create a list of tuples consisting of:

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

zip processing sequence can be of any length, but is determined by the length of the shortest sequence:

#接上面代码
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, function elements reversed sequence reverse order:

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

 

Guess you like

Origin blog.csdn.net/pz789as/article/details/93736795