Reference: Https://docs.python.org/2.7/reference/compound_stmts.html#while
Https://www.cnblogs.com/lclq/p/5586198.html (Python's operations and expressions)
https://www.zhihu.com/question/20829330 (Python iterator)
Https://www.cnblogs.com/devin-guwz/p/5738676.html (Python introductory example)
True and False in Python:
Not 0 digits are true, otherwise false
Non-empty object is true, otherwise false
None is always False
Different types of comparison methods:
Numbers: Comparing by relative size
String: Comparison by character-by-word in dictionary order
Lists and tuples: Comparing parts of content from left to right
Dictionaries: Comparing the list of (keys, values) after sorting
If condition statement:
IF_STMT:: = "if" expression ":" Suite
("elif" expression ":" Suite) *
["Else" ":" Suite]
While condition statement:
WHILE_STMT:: = "while" expression ":" Suite
["Else" ":" Suite]
For condition statement:
FOR_STMT:: = "for" target_list "in" Expression_list ":" Suite
["Else" ":" Suite]
这些条件语句跟shell脚本没太大区别,主要差别在于: 1.python用相同的空格在区分结构体(这是为了强制大家保持良好编程风格的缘故,而shell脚本而有对应的结束符,比如if有fi对应) 2.while和for多了个else控制结构,这个else是指在循环正常执行完成后,最后执行一次
Iterators and generators:
迭代器提供了一个统一的访问集合的接口。只要是实现了__iter__()或__getitem__()方法的对象,就可以使用迭代器进行访问。生成器也可以迭代,但是生成器不会把结果保存在一个系列中,而是保存生成器的状态,在每次进行迭代时返回一个值,直到遇到StopIteration异常结束两种都是类似的东西,主要差别在于:迭代器一次就生成了所有可能用到的对象,而生成器一次只生成一个需要用到的对象
Examples:
1. Ask for all even numbers within 100 and
Using while:
Sum=0
I=0
While i<=100:
Sum+=i
i+=2
使用for: sum=0 for i in range(1,101): if i%2==0: sum+=i
2. Create a list containing all the odd numbers within 100
Using while:
L1=[]
I=1
While i<100:
L1.append (i)
i+=2
Use for:
L1=[]
For I in Range (1,101):
If i%2!=0:
L1.append (i)
使用expression for target_list "in" expression_list if expression_list 表达式: l2=[i for i in range(1,100)if i%2!=0]
3. List l1=[0,1,2,3,4,5,6] List l2=[' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G '], with the first list as the key, the second list as the value, generate dictionary D
D={l1[i]:l2[i] for I in range (0,7)}
3.1 Print the key-value pairs in dictionary D individually
for (K,V) in D.items ():
Print K,v
4. Generate a new list of lists that belong to the list l1=[1,2,3,4,5,6], which are not part of l2=[2,3,4] L3
L3=[i for i in L1 if I is not in L2]
Python control structures, iterators, and generators (personal notes)