iterative tool

In python, there are some common functions when iterating over sequences or other iterable objects

1. Parallel iteration:

A program can iterate over two sequences at the same time:

student=[ ' xiaoming ' , ' xiaohong ' , ' xiaogang ' ]
number =[1001,1002,1003 ]
 for i in range(len(student)):
     print (student[i], ' The student number is: ' ,number[i]) #Output 

:
Xiaoming's student number is: 1001
xiaohong's student ID is: 1002
xiaogang's student ID is: 1003

2.zip function

In python, the built-in zip function is used to iterate in parallel, combining two sequences together and returning a list of tuples, for example:

student=[ ' xiaoming ' , ' xiaohong ' , ' xiaogang ' ]
number =[1001,1002,1003 ]
 for name,num in zip(student,number):
     print (name, ' the student number is: ' ,num) #Output 

:
xiaoming's student number is: 1001
xiaohong's student number is : 1002
Xiaogang's student ID is: 1003

The result is the same as above.

The zip function can be used for any number of sequences, and can cope with sequences of unequal length, stopping when short sequences are "used up".

student=[ ' xiaoming ' , ' xiaohong ' , ' xiaogang ' , ' xiaopang ' , ' xiaozhi ' ]
number =[1001,1002,1003 ]
 for name,num in zip(student,number):
     print (name, ' the student number is: ' ,num) 
#output
xiaoming's student number is: 1001
xiaohong's student number is: 1002
Xiaogang's student ID is: 1003

It can be seen from the output results that the zip function is subject to the short sequence. When the short sequence traversal ends, the for loop will end.

3. Flip and Sort Iteration

The reverse and sort methods are specific to lists, while the reversed() and sorted() functions work on all sequences and iterables, but instead of modifying the object in place, return the reversed or sorted version.

a=[1,2,5,3,3,9,4,6,4,3]
b=[2,3,4,5,7,6,1,6,6,3]
a.sort()
print(a)
b.reverse()
print(b)

c
= " hello world " d = sorted(c) print (d)
e
= " hello world " f = list(reversed(e))#reverse() function returns an iterable object, so it needs to be converted into a list print (f)
g
= " hello world " h = '' .join(reversed(g)) print (h)

# output
[1, 2, 3, 3, 3, 4, 4, 5, 6, 9 ]
[3, 6, 6, 1, 6, 7, 5, 4, 3, 2]
[' ', 'd', 'e', ​​'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
['d', 'l','r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'h']
dlrow olleh

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325119671&siteId=291194637