colors=['red','green','blue'] for color in enumerate(colors): print (color) #Output: (0, 'red') (1, 'green') (2, 'blue') |
colors=['red','green','blue'] for color in enumerate(colors,5): print (color) ''' Output: (5, 'red') (6, 'green') (7, 'blue') ''' |
s='python' for i in enumerate(s): print (i) ''' #Output: (0, 'p') (1, 'y') (2, 't') (3, 'h') (4, 'o') (5, 'n') ''' |
num = [1, 2, 3] colors= ['red', 'blue', 'green'] for i in zip(num, colors): print(i) ''' Output: (1, 'red') (2, 'blue') (3, 'green') '' |
colors=['red','green','blue'] num=[1,2,3,4,5,6,7,8,9,10] for i in zip(colors,num): print (i) ''' Output: ('red', 1) ('green', 2) ('blue', 3) ''' |
colors=['red','apple','three'] num=[1,2,3] alp=['a','b','c'] for i in zip(colors,num,alp): print (i) ''' Output: ('red', 1, 'a') ('apple', 2, 'b') ('three', 3, 'c') ''' |
from itertools import zip_longest colors=['red','apple','three'] num=[1,2,3,4,5] for i in zip_longest(colors,num): print (i) ''' Output: ('red', 1) ('apple', 2) ('three', 3) (None, 4) (None, 5) ''' |
from itertools import zip_longest colors=['red','apple','three'] num=[1,2,3,4,5] for i in zip_longest(colors,num,fillvalue='z'): print (i) ''' Output: ('red', 1) ('apple', 2) ('three', 3) ('z', 4) ('z', 5) ''' |
num=[10,5,20,25,30,40,35] for i in sorted(num): print (i) ''' Output: 5 10 20 25 30 35 40 ''' |
num=[10,5,20,25,30,40,35] for i in sorted(num,reverse=True): print (i) ''' Output: 40 35 30 25 20 10 5 ''' |
d={'f':1,'b':4,'a':3,'e':9,'c':2} for i in sorted(d.items()): print (i) #Output: ('a', 3) ('b', 4) ('c', 2) ('e', 9) ('f', 1) |
d={'f':1,'b':4,'a':3,'e':9,'c':2} #sorting by values in the dictionary for i in sorted(d.items(),key=lambda item:item[1]): print (i) #Output: ('f', 1) ('c', 2) ('a', 3) ('b', 4) ('e', 9) |
reversed(seq): |
colors=['red','green','blue','yellow'] for i in reversed(colors): print (i) ''' Output: yellow blue green red ''' |
d={'a':1,'b':2,'c':3} for k,v in d.items(): print (k,v) #Output: a 1 b 2 c 3 |
d={'a':1,'b':2,'c':3} for k,v in d.copy().items(): if v%2==0: del d[k] print (d) #Output:{'a': 1, 'c': 3} |
d={'a':1,'b':2,'c':3} d1={} for k,v in d.items(): if v%2!=0: d1[k]=v print (d1) #Output:{'a': 1, 'c': 3} print (d) #Output:{'a': 1, 'b': 2, 'c': 3} |
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) | Powered by Discuz! X3.2 |