Conclusion Syntax thought
Ternary expressions with the condition is true the results, if + determine the conditions, else + condition is false results
List comprehensions is the result on the front, want to follow the circulation loop iterations can be something (iterable)
And it is different from the list of glyphs '{}' and still form a Dictionary
Remember there are screening, multiple nested
With a little ,,,,
A triplet of expressions
Format: condition results when true, if + determination condition, else + result of the condition is false
A triplet of expressions of an idea: if a <100 is true, True: corresponds to a result, in turn, there will be another result
chestnut:
A = . 1
B = 2
C = 'JH handsome world' IF A < 100 the else 'is the world's most handsome JH'
# a loading force to the take over colleagues read hit someone
#c = ({True : 'jh handsome world', False: 'Less'} [a <100]) # thought it
Print ( C )
List comprehensions
Very simple
Is the result on the front, want to follow the circulation loop iterations can be something (iterable)
[Variables (variables after processing) for the variable in iterable]
L1 = [ I for I in Range ( 1 , 101 )]
Print ( L1 ) # output [ 1 , 2 , 3 , 4 , 5 , 6 , .. .100 ]
Complex list of expressions that can transform and filter on the original list.
Such as:
# 1-10 conceivable composed of an even number squared List
Example = [ I ** 2 for I in Range ( . 1 , . 11 ) IF I % 2 == 0 ]
Print ( Example )
Number list in a list NESTED want multiple nested list length is greater than 1 in the list is a multiple of the square of composition 2
example4 = [[1,2,3],[4,5,6],[7,8,9],[10]]
exmaple5 = [j**2 for i in example2 if len(i)>1 for j in i if j%2 == 0]
print(exmaple5)
Dictionary of formula
And it is different from the list of glyphs '{}'
Printing [0: 9] Results ** 2
Print ({ I : I ** 2 for I in Range ( 10 )})
# result is {0: 0, 1: 1, 2: 4, 3: 9, 4:16, 5:25, 6:36, 7:49 8: 64, nine eighty-one}
Printing judgment [0: 9] 2% of the Boolean value 0 is returned dictionaries
b={i:i% 2==0 for i in range(10)}
print(b)
zip () method
Generated by decompressing a dictionary function
keys = ['name', 'age', 'gender']
values = ['nk', 19, 'male']
res = zip(keys, values)
print(F"zip(keys,values): {zip(keys,values)}")
info_dict = {k: v for k, v in res}
print(f"info_dict: {info_dict}")
zip(keys,values): <zip object at 0x11074c088>
info_dict: {'name': 'nk', 'age': 19, 'sex': 'male'}
练习
练习一:编写名为collatz(number)的函数;实现的功能:参数为偶数时,打印num// 2;参数为奇数时,打印3*number + 1
num=int(input('please input integer.'))
print (num//2 if num%==0 else num*3+1)
...