Python语言中的常用技巧

技巧罗列一下,以备后续常用

1.包装与解包

a = (1,2,3)
x,y,z = a

2.判断元素是否存在

## check whether it exists.
bb = ['a', 'b', 'c']
if 'a' in bb:
    print("let it be...")

cc ={'a': 'a', 'b':'b', 'c':'c'}
print('c' in cc)

"s" in "stirng"

"string".startswith('s')
"string".endswith('g')

3.数组元素的切割

## 数组切割
l2 = [1,2,3,4,5]
l2[:4]
l2[-2:]
l2[3:]

## 1, 3, 5
l2[::2]
l2[-1]

4.三元表达式

# 三元表达式
a if b else c

5.数组操作的快捷方式

m = list(), dict(), 

m = (1,2,3,4)
n = [i*2 for i in m]

d = [x for i in m if i% 2 == 2]

e = {x:x%2 == 0 for x in m}

m = [1,2,3,4,5]
i = (x for x in m)

6.lambda操作

## lambda synthex
test =lambda x: (x+2)

def test(x):
    x+2

print(test(3)

7.数组集合操作


[1,2] + [3,4] ==> [1,2,3,4]

[1,2].extend([3,4])  old array

[1,2] * 2 ==> [1,2,1,2]

"xx" * 2 ==> "xxxx"

team = ['ab', 'cd', 'ef']

for index, ele in enumerate(team):
    print(str(index) + ":" +ele)

8.常用的集合函数

# filter
nums = [1,2,3,4]

##generator
## filter:  filte
## map:  do action for every element
## 
l = filter(lambda x: x%2==0, nums)
for i in l:
    print(i)

## zip
nums1 = [1,2,3,4]
nums2 = [5,6,7,8]

l = zip(nums1, nums2)
for i in l:
    print(i)

## reduce
from functools import reduce
teams = [1,2,3,4]
l = reduce(lambda x,y: x+y, teams)
for i in l:
    print(i)

这类是基于规则的操作函数, 可以基于lambda的快捷函数来实现,也可以自行定义。这类函数操作的结果都是generator,需要遍历之后方可访问。

猜你喜欢

转载自blog.csdn.net/blueheart20/article/details/81636996