Python small function

1.zip

The zip() function is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return a list of these tuples.

If the number of elements of each iterator is inconsistent, the length of the returned list is the same as that of the shortest object. Using the * operator, the tuple can be decompressed into a list.

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 is an unordered and non-repeating collection of elements

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

3.map

Map the specified sequence according to the provided function and return an iterator.

def square(x):
    return x**2

print(list(map(square,[1,2,3,4])))#[1,4,9,16]
a = "12334"
map(int,a)#Convert each element of a to an integer
Out[24]: <map at 0x1c1001f15f8>
list(map(int,a))
Out[25]: [1, 2, 3, 3, 4]

4.all

The all() function is used to determine whether all elements in the given iterable parameter iterable are not 0, '', False or the iterable is empty, if so, return True, otherwise return False.

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

5.Python generates a string of az

import string
string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

6. Convert letters to integers for -ord

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

7. Improvement arrangement

math.ceil()

8. Calculate a^x=b

math.log(b,a)#Note the order

9. Permutation and combination

import itertools
a = [1,2,3]
list(itertools.permutations(a,2))#Arrange, select 2 numbers from a to arrange, the default is to arrange all numbers, each element is a tuple
Out[44]: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
list(itertools.combinations(a,2))#combinations
Out[45]: [(1, 2), (1, 3), (2, 3)]

10.int converts the string to a decimal integer, the base of the original number of the second parameter

int("100",2)
4
int("Ff",16)
255
int("FG",16)#When the data is wrong, throw an exception
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 16: 'FG'

11. Calculate the running time of the program

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



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326047623&siteId=291194637