python using \ Advanced \ tips

1. Use of a ternary operator

#[on_true] if [expression] else [on_false]


a, b = 999, 34
result = a if a%b==0 else b


def subtract(a,b):
  return a-b
def add(a,b):
  return a+b
pd = 1
print( (subtract if pd else add)(23,5) )

 

2. List / string in reverse order

lis = [1,2,3,4,5]
lis[::-1]
# print(lis)
# [5,4,3,2,1]

 

3. Use enumerate enumeration of

for i,item in enumerate('abcdef'):
  print(i,' ',item)


'''
0 a
1 b
2 c
3 d
4 e
5 f
'''

 

>>> list(enumerate('abc'))

[(0, 'a'), (1, 'b'), (2, 'c')]

>>> list(enumerate('abc', 1))

[(1, 'a'), (2, 'b'), (3, 'c')]

 

4. Dictionary / set parsing

This should be used a lot, we are all familiar

# The following is a partial list of ascii 
>> {_ascii = CHR (I): I for I in Range (32,127)}
{ '': 32, '!': 33 is, ' "': 34 is, '#': 35, '$': 36 '%': 37, '&': 38, '' ': 39' ( ': 40') ': 41,' * ': 42,' + ': 43', ': 44,' - ': 45' ': 46' / ': 47}.

 

The combination string splicing / "" .join use

# All the elements are combined into a string in the list 
>> A = [ "Google", "IS", "awsome", "!"]
>> "" .join (A)
Google IS awsome!
>> "." the Join (A)
googleisawsome!
>> "_." the Join (A)
google_is_awsome_!

 

6. Sort by [] key element dictionary

>> dict = {'apple':10, 'orange':28, 'banana':5, 'tomato':1}
>> sorted(dict.items(),key=lambda x:x[1])
[('tomato', 1), ('banana', 5), ('apple', 10), ('orange', 28)]
>> sorted(dict.items(),key=lambda x:x[0])
[('apple', 10), ('banana', 5), ('orange', 28), ('tomato', 1)]

 

7.for else use

Yes

 

8. dictionary get () method

>> d = {'A':92,'B':93}
>> d.get('B')
93
>> d.get('C','None')
'None'

 

7.for else use

pd = 11
for i in range(5):
  print(i)
  if pd==i:
    break;
else:
  print("yeaho??")

'''

Output

0 1 2 3 4 yeaho ??

If pd = 3, the output

0 1 2 3

'''

 

8. The two-dimensional matrix transpose

# Directly zip () function 

>> Matrix = [[ 'A', 'B'], [ 'C', 'D'], [ 'E', 'F']]
>> List (ZIP (* Matrix ))
[( 'A', 'C', 'E'), ( 'B', 'D', 'F')]

 

Guess you like

Origin www.cnblogs.com/dynmi/p/12232121.html