Pythonic的代码(1)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_1290259791/article/details/82634160

Pythonic的代码(1)

爱上Python就是喜欢他精简的语法,写出Pythonic的代码,Python就要有自己优雅的写法。我认为好的程序员在写代码时,应该追求代码的正确性,简洁性和可读性,就是pythonic的精神所在。

1、变量值交换

a, b = b, a

2、生成字典序列

>>> result = dict(zip('abcd',range(4)))
>>> print(result)
{'a': 0, 'b': 1, 'c': 2, 'd': 3}

3、三目运算

>>> ok = 1
>>> result = 'ok' if ok == 1 else 'no'
>>> print(result)
ok

4、推导式

列表:[x*x for x in range(20) if x % 3==0]
集合:{x * x for x in range(20) if x % 3==0}
字典:{x : x *x for x in range(20) if x % 3 ==0}
生成器:(x*x for x in range(10))

5、反转字符串

>>> result = [1,2,3,4,5]
>>> print(result[::-1])
[5, 4, 3, 2, 1]

6、item遍历map

>>> temp = {'a':1,'b':2,'c':3,'d':4}
>>> for k, v in temp.items():
...     print(k,v)
... 
a 1
b 2
c 3
d 4

7、字符串的连接

>>> temp = ['a', 'b', 'c']
>>> print(''.join(temp))
abc

8、求和 最大值 最小值 乘积和

>>> temp = [1,2,3,4,5]
>>> sum(temp)
15
>>> min(temp)
1
>>> max(temp)
5
>>> from operator import mul
>>> from functools import reduce
>>> reduce(mul, temp)
120
>>> 

9、for..else..语句

当没有进行break的时候,for循环完后就会执行else的语句

>>> for i in range(5):
...     if i == 5:
...             print(i)
...             break
... else:
...     print('里面没有5')
... 
里面没有5

10、enumerate的用法

enumerate(temp, [start=0]):temp迭代对象,start下标起始的位置。

>>> for k, v in enumerate(temp,2):
...     print(k, v)
... 
2 1
3 2
4 3
5 4
6 5

猜你喜欢

转载自blog.csdn.net/qq_1290259791/article/details/82634160
今日推荐