Python小函数

1.zip

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

a = [1,2,3,4]
b = [2,3,4,5]
print(list(zip(a,b)))#[(1,2),(2,3),(3,4),(4,5)]

2.set

set是一个无序且不重复的元素集合

s = "fshdof"
set(s)
Out[18]: {'d', 'f', 'h', 'o', 's'}

3.map

根据提供的函数对指定的序列做映射,返回迭代器。

def square(x):
    return x**2

print(list(map(square,[1,2,3,4])))#[1,4,9,16]
a = "12334"
map(int,a)#将a的每一个元素转换为整数
Out[24]: <map at 0x1c1001f15f8>
list(map(int,a))
Out[25]: [1, 2, 3, 3, 4]

4.all

all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否不为 0、''、False 或者 iterable 为空,如果是返回 True,否则返回 False。

all(["a","b","c","d"])
True
all(["a","b","","d"])
False
all([])
True
all([True,False])
False

5.Python产生a-z的字符串

import string
string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

6.将字母转换为对于的整数-ord

ord("a")
Out[13]: 97

7.向上取整

math.ceil()

8.计算a^x=b

math.log(b,a)#注意顺序

9.排列组合

import itertools
a = [1,2,3]
list(itertools.permutations(a,2))#排列,从a中选择2个数进行排列,默认是对所有数进行排列,每一个元素是tuple
Out[44]: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
list(itertools.combinations(a,2))#组合
Out[45]: [(1, 2), (1, 3), (2, 3)]

10.int 将字符串转换为十进制整数,第二个参数原来数的基底

int("100",2)
4
int("Ff",16)
255
int("FG",16)#数据不对时,抛出异常
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 16: 'FG'

11.计算程序运行时间

https://blog.csdn.net/chichoxian/article/details/53108365



猜你喜欢

转载自blog.csdn.net/hhhhhyyyyy8/article/details/79814462