Python advanced built-in functions

Python advanced built-in functions

2020-11-17

zip

cycle

x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
ans = []
for i in range(len(x)):
    ans.append(x[i] + y[i])
ans
# zip实现
x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
ans = []
for x, y in zip(x, y):
    ans.append(x + y)
ans

Accept data type

a = [1, 2]
list(zip(a))
b = (1, 2)
list(zip(b))
c = {
    
    1, 2}
list(zip(c))
d = 'python'
list(zip(d))

result

[(1,), (2,)]
[(1,), (2,)]
[(1,), (2,)]
[('p',), ('y',), ('t',), ('h',), ('o',), ('n',)]
# 接受多个序列
a = [1, 2, 3]
b = (4, 5, 6)
c = {
    
    7, 8, 9}
d = 'zip'
list(zip(a, b, c, d))
[(1, 4, 8, 'z'), (2, 5, 9, 'i'), (3, 6, 7, 'p')]
# 处理不同长度
# 选择最小的
a = [1, 2]
b = (2, 3, 4)
c = 'string'
list(zip(a, b, c))
[(1, 2, 's'), (2, 3, 't')]

filter

Filter itself means to filter: it is to directly filter and discard the data that does not meet our requirements, leaving those that meet the requirements.

Custom function

# 选出1-25奇数
def get_jishu(x):
    return x % 2 == 1
list(filter(get_jishu, list(range(25))))
# lambda 表达式
list(filter(lambda x: x % 3 == 1, list(range(25))))
# 筛选不满足要求的字符串
str_list = ["guangzhou","shanghai","shenzhen","changsha"]
list(filter(lambda x: x != "shenzhen", str_list)) 

enumberate

Get subscripts

test = ['python', 'java', 'c', 'php']
for idx, item in list(enumerate(test)):
    print(idx, item)
0 python
1 java
2 c
3 php

reversed/reverse

Only list can be used

a_list = [1, 3, 4]

# 列表内部的用法
a_list.reverse()
a_list
# 挺多数据类型都有reversed
a_list = list(reversed(a_list))
a_list
[4, 3, 1]
[1, 3, 4]

eval

eval Directly return the result of the expression passed in the string

Simply put, it is to display the string, And convert the corresponding data type

str1 = '[1, 2, 3, 4]'
str2 = '(1, )'
str3 = '{1, 3}'

type(eval(str1))
type(eval(str2))
type(eval(str3))

result

list
tuple
set

Guess you like

Origin blog.csdn.net/weixin_44179485/article/details/114125822