python使用\进阶\小技巧

1.三元运算的使用

#[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.列表/字符串的逆序

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

 

3.枚举enumerate的使用

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.字典/集合 解析

这个应该用的很多了,大家都熟悉

#下面是ascii表的部分
>> _ascii  = {chr(i): i for i in range(32,127)}
{' ': 32, '!': 33, '"': 34, '#': 35, '$': 36, '%': 37, '&': 38, "'": 39, '(': 40, ')': 41, '*': 42, '+': 43, ',': 44, '-': 45, '.': 46, '/': 47}

 

5.字符串组合拼接 / "".join的使用

# 将列表中的所有元素组合成字符串
>> a = ["google ","is ","awsome","!"]
>> " ".join(a)
google is awsome!
>> "".join(a)
googleisawsome!
>> "_".join(a)
google_is_awsome_!

 

6.通过【键】排序字典元素

>> 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的使用

是的

 

8.字典get()方法

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

 

7.for else的使用

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

'''

输出为

0 1 2 3 4 yeaho??

如果pd=3,输出为

0 1 2 3

'''

 

8.二维矩阵的转置

# 直接使用zip()函数

>> matrix = [['a','b'],['c','d'],['e','f']]
>>list(zip(*matrix))
[('a', 'c', 'e'), ('b', 'd', 'f')]

 我第一次在python中见到zip时,以为zip()函数是打包压缩文件的意思哈哈哈,

zip()其实是将列表打包成元组的函数:

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]

 

posted @ 2020-01-24 14:08  dynmi  阅读(344)  评论(0编辑  收藏  举报