Python for loop clever use (iteration, list generation), python generation
IntroductionWe can use the for loop to iterate the list, tuple, dict, set, and string. dict is not sequential in storage, so iteration (traversal) the order of the output values also changes. Iteration (traversal)
#!/usr/bin/env python3#-*- coding:utf-8 -*-vlist=['a','b','c']vtuple=('a','b','c')vdict={'a': 1, 'b': 2, 'c': 3}vset={'a','b','c'}vstr='abc'for x in vlist: print('list:',x)for x in vtuple: print('tuple:',x)for x in vdict: print('dict:',x)for x in vset: print('set:',x)for x in vstr: print('str:',x)
list: alist: blist: ctuple: atuple: btuple: cdict: cdict: adict: bset: aset: bset: cstr: astr: bstr: c
You can use the Iterable type of the collections module to determine whether an object is an iteratable object:
>>> from collections import Iterable>>> isinstance('abc', Iterable) True>>> isinstance([1,2,3], Iterable) True>>> isinstance(123, Iterable) False
Multi-value for operation
>>> for x, y in [(1, 1), (2, 4), (3, 9)]: print(x,y) 1 12 43 9
Generate subscript
>>> for x, y in enumerate(['a', 'b', 'c']): print(x, y) 0 a1 b2 c
Generate list
1. List the squares ranging from 1 to 10
#!/usr/bin/env python3#-*- coding:utf-8 -*-L=[]for x in range(1,11): L.append(x*x)print(L)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Python provides a simpler way to handle this requirement.
>>> [x*x for x in range(1,11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
2. Add judgment Conditions
Retrieve only the even number in the list
>>> [x*x for x in range(1,11) if x%2==0][4, 16, 36, 64, 100]
3. simultaneous judgment of multiple
>>> [m+n for m in 'ABC' for n in'abc']['Aa', 'Ab', 'Ac', 'Ba', 'Bb', 'Bc', 'Ca', 'Cb', 'Cc']
4. Obtain the value in dict
Generally, for operations can only obtain keys in dict, but cannot obtain values. You can use items to obtain values.
>>> d={'a': 'A', 'b': 'B', 'c': 'C'}>>> [k + '=' + v for k,v in d.items()]['c=C', 'a=A', 'b=B']
Note: Because dict is a single key-value, you cannot directly use k, v for k, v to represent k, v is multiple keys instead of key-value before, therefore, only calculation can be performed. However, if calculation is performed, the key and value must be of the same data type. Otherwise, the + operation cannot be performed.
For data types with different keys and values, you can use a common for loop and print the output.
#!/usr/bin/env python3#-*- coding:utf-8 -*-d={'a': 1, 'b': 2,'c': 3}for k,v in d.items(): print(k,'=',v)
5. Convert all strings in the list to lowercase letters.
>>> L = ['Hello', 'World', 'IBM', 'Apple']>>> [s.lower() for s in L]['hello', 'world', 'ibm', 'apple']
Summary
Python syntax is too clever, mainly due to its powerful library, so that python can be used with less underlying code.
Note: Author: pursuer. chen Blog: http://www.cnblogs.com/chenmh All essays on this site are original. You are welcome to repost them. However, you must indicate the source of the article and clearly give the link at the beginning of the article. Welcome to discussion |