Summary of commonly used functions in Python interview questions

1. Usage of join() in Python

'a'.join(s) : Returns a new string with the string a inserted between each element of s.
Parameter description
a: separator, can be empty
s: element sequence to be connected, string, tuple, dictionary The
above syntax is: use a as a separator, combine all elements of s into a new string
return value : Returns a string generated by concatenating elements with a delimiter a 

Supplement: os.path.join() function
Syntax: os.path.join(path1[,path2[,…]])
Return value: Return after combining multiple paths
Note: The parameters before the first absolute path will be replaced neglect 

#对序列进行操作 使用‘ ’作为分隔符
s= ['hello' , 'how' , 'are' , 'you' ]
print(' '.join(s))
#对字符串进行操作
# 输出 hello how are you

# 对元祖进行操作
s = ('hello' ,'good' , 'boy', 'liu')
print(':'.join(s))
# 输出 hello:good:boy:liu

# 对字典进行操作
s = {'hello':1 , 'good':2, 'boy':3}
print(':'.join(s))
# 输出 hello:good:boy

# 合并目录
import  os
print(os.path.join('/hello/','good/boy/','xu'))
# 输出 /hello/good/boy/liu


>>> s='abcdefg'
>>> '%'.join(s)
'a%b%c%d%e%f%g'
>>> '%'.join(s.split(c))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> '%'.join(s.split('c'))
'ab%defg'
>>> s[:-1]
'abcdef'
>>> s[:len(s)]
'abcdefg'
>>> s[::]
'abcdefg'
>>> s[1:len(s):2]
'bdf'

2. list(s) function

The list(s) function converts the sequence s into a list
Description: The list() method is used to convert a tuple or string into a list.
Note: Tuples and lists are very similar, the difference is that the element values ​​of tuples cannot be modified, tuples are placed in brackets, and lists are placed in square brackets.
Syntax: list( seq )
parameter seq is a tuple or string to be converted to a list.
Return value: return list.

[Extension] : list1[0] returns the element value in the list list1; list1[:1] returns the list.
>>> list1 = ['1', '2']
>>> list1[0]
'1'
>>> list1[:1]
['1']

>>> s='hello'
>>> print(list(s))
['h', 'e', 'l', 'l', 'o']

>>> s=('hello','world','123')
>>> print(list(s))
['hello', 'world', '123']

3.  There are no ++ and -- operations in Python, and the self-increment and self-decrement operations can be done through +=/-=

4. split() function

string.split(str, num)

str – delimiter, the default is all null characters, including spaces, newlines (\n), tabs (\t), etc.
num – the number of splits. Specifies the number of splits to perform. The default is -1, which is "all occurrences".

Description: split() slices the string by the specified delimiter, if the parameter num has a specified value, separate num+1 substrings. It divides a string into a specified number of substrings according to the specified delimiter, and then puts them into a list, where each word is a list item.

#例1:
>>> a="I love China"
>>> a.split()   # 分隔符为空,分割次数默认
['I', 'love', 'China']

#例2:
>>> b="I love China, and you, you"
>>> b.split(", ")    # 使用逗号和空格作为分隔符
['I love China', 'and you', 'you']
 
#例3:
>>> c="I#love#China#andyou#you"
>>> c.split("#")   #使用#作为分隔符
['I', 'love', 'China', 'andyou', 'you']

#例4:
>>> d="I#love#China#andyou#you"
>>> d.split("#",1)   # 将 max值为 1,将返回包含 2 个元素的列表
['I', 'love#China#andyou#you']
 
#例5:
>>> e="with great power comes great responsibility. I love China and you you"
>>> e.split(" ",15) #空格为分隔符
['with', 'great', 'power', 'comes', 'great', 'responsibility.', 'I', 'love', 'China', 'and', 'you', 'you'] 

5. Use the [::-1] python string slicing method  skillfully

[::-1] is a reverse order operation, the core of which is slicing. Given a list/character a, the syntax for slicing is b = a[start_index: end_index: step]

s1 = s[: : -1] is actually s1 = s[-1: : -1]

>>> s='the sky is blue'
>>> print(list(s)[::-1])
['e', 'u', 'l', 'b', ' ', 's', 'i', ' ', 'y', 'k', 's', ' ', 'e', 'h', 't']
>>> print(s.split()[::-1])
['blue', 'is', 'sky', 'the']
>>> print(s[::-1])
eulb si yks eht
>>> a=['h','e','ll','o']
>>> print(a[::-1])
['o', 'll', 'e', 'h']

6. Counter() function 

Counter()  is  a function in the collections library, which can be used to count the number of occurrences of each element in an iterable object such as  a python list, string, tuple, etc. , that is, count the word frequency and return a dictionary .

from collections import Counter
 
nums = [1, 1, 1, 6, 6, 6, 7, 8]
count = Counter(nums)  # 统计词频
for k, v in count.items():
    print(k, v)
print(count)
"""
输出:
1 3
6 3
7 1
8 1
Counter({1: 3, 6: 3, 7: 1, 8: 1})
"""

After using  Counter  to count the word frequency, you can use  the most_common  method to find the k numbers with the highest frequency and the number of occurrences.

from collections import Counter
 
nums = [1, 1, 1, 6, 6, 6, 7, 8]
 
count = Counter(nums)
 
ansdict = count.most_common(2)  # 返回出现次数最多的两个数及其出现的次数
print(ansdict) # 注意输出格式
ans = []
for i in range(len(ansdict)):
    ans.append(ansdict[i][0])  # 提取出出现次数最多的两个数
print(ans)
 
"""
输出:
[(1, 3), (6, 3)]
[1, 6]
"""

7. The get()  method  of Dictionary

 The get() function returns the value for the specified key.

dict.get(key[, value]) 
  • key – The key in the dictionary to look up.
  • value -- optional, if the value for the specified key does not exist, return the default value.
  • Returns the value of the specified key, if the key is not in the dictionary returns the default value of  None  or the default value set.
tinydict = {'Name': 'Runoob', 'Age': 27}

print ("Age : %s" %  tinydict.get('Age'))

# 没有设置 Sex,也没有设置默认的值,输出 None
print ("Sex : %s" %  tinydict.get('Sex'))  

# 没有设置 Salary,输出默认的值  0.0
print ('Salary: %s' % tinydict.get('Salary', 0.0))

# 输出
Age : 27
Sex : None
Salary: 0.0

8. stack stack method: stack.pop() pops the stack, stack.append() pushes it into the stack, stack[-1] indicating the last element in the stack

9.  The zip()  and zip(*)  functions are often used for matrix transposition (rows become columns)

(1) When passing in a parameter:

zip(iteration): Its parameters are multiple iterable objects, and its function is to aggregate the elements in each iterable object. Take a tuple
in turn from the iteration to form a tuple.

(2) zip(a,b) when two parameters are passed in:

The zip() function takes out one element from a and b respectively to form a tuple, and then combines the successively formed tuples into a new iterator —new zip type data.

in,

- The dimensions of a and b are required to be the same. When the two have the same number of rows and columns, the corresponding position elements can be combined normally; -
When the number of rows or columns of a and b is different, take the structure of the two The minimum number of rows and columns, according to the minimum number of rows and columns to combine the elements at the corresponding position; this is equivalent to calling the itertools.zip_longest(*iterables) function.

>>> grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
>>> list(zip(*grid))
[(3, 2, 9, 0), (0, 4, 2, 3), (8, 5, 6, 1), (4, 7, 3, 0)]
>>> list(zip(grid))
[([3, 0, 8, 4],), ([2, 4, 5, 7],), ([9, 2, 6, 3],), ([0, 3, 1, 0],)]

10. tuple()  function 

The tuple() function is used to convert lists, ranges, etc. into tuples.

Note : Tuples and lists are very similar, but the biggest difference between lists and tuples is that tuples are immutable and lists are mutable. The operations supported by tuples are basically supported by lists; lists support the modification of elements, but tuples do not. From this perspective, lists can be thought of as an enhanced version of tuples.

Although lists can be used instead of tuples most of the time, it is safer to use tuples instead of lists if the program does not need to modify the elements contained in the list.

Usage: tuple(list/range...), returns a tuple.

a = [1,2] #list
b = {"1":2,"3":3} #dict
c = {1,2,3,3}  #set
d = range(2,10,2) #range
print(tuple(a))
print(tuple(b))
print(tuple(c))
print(tuple(d))

#输出
(1, 2)
('1', '3')
(1, 2, 3)
(2, 4, 6, 8)

11.  collections.deque() library function that comes with python 

Collections is a library that comes with python . collections.deque() is a double-ended queue , which can realize the function of adding or removing elements at the left and right ends. The time complexity is O(1), and it has the properties of stack and queue at the same time.

append() : Add elements from the right end, the same as list.

appendleft() : add elements from the left

extend() : Add iterable objects one by one from the right end, the same as list, iterable objects in Python are: list, tuple, dictionary, string.

extendleft() : Add iterable objects one by one from the left end. The iterable objects in Python include: lists, tuples, dictionaries, and strings.

pop() : Remove an element in the list (by default the rightmost element), and return the value of the element (与list同), if there is no element, an IndexError will be reported.

popleft() : Remove an element in the list (the leftmost element by default), and return the value of the element. If there is no element, an IndexError will be reported.

count() : Count the number of elements in the queue (与list同).

insert(index,obj) : Insert an element at the specified position (same as list).

rotate(n) : Reverse n steps from the right, or from the left if n is negative. For example: d.rotate(1) is equal to d.appendleft(d.pop())

maxlen : read-only attribute, the maximum length limited by deque, if none, returns None. When a deque with a limited length adds more than the limited number of items, the items on the other side are automatically deleted.

remove() : Remove the first occurrence of the element, if not found, report ValueError.

clear() : Delete all the elements in the deque, and the final length is 0.

q = collections.deque()
q.append('a') # 在队列右边添加元素‘a’,deque(['a'])
q.appendleft('b') # 在队列左边添加元素‘b’,deque(['b', 'a'])
q.extend('c') # 在队列右边添加序列,deque(['b', 'a', 'c])
q.extendleft('d') # 在队列左边添加序列,deque(['d', 'b', 'a', 'c'])
# 关于append和extend的区别
# append添加一整个对象,不管该对象是什么类型,都作为一个整体全部添加进来,如整型数据或者一整个列表
# extend添加一个序列,只能是相同类型的元素,如该题中的字符/字符串或者是由字符和字符串组成的列表['st','e'],其他类型的数据如整数就会报错
q.append(['e','f'] # deque(['d', 'b', 'a', 'c', ['e', 'f']])
q.append(4) # deque(['d', 'b', 'a', 'c', ['e', 'f'], 4])
q.extend([g', 'h'] # deque(['d', 'b', 'a', 'c', ['e', 'f'], 4, 'g', 'h'])
q.append(5) # 报错 TypeError: 'int' object is not iterable
# 取出元素
q.pop() # 右端取出
q.popleft() # 左端取出

12.  enumerate() function 

The enumerate() function is used to combine a traversable data object (such as a list, tuple or string) into an index sequence, listing data and data subscripts at the same time.

That is to say, for an iterable (iterable)/traversable object (such as a list, a string), enumerate forms it into an index sequence, which can be used to obtain both the index and the value. Usually used in for loops.

Syntax: enumerate(sequence[,startindex=0])

parameter:

  • sequence – a sequence, iterator, or other object that supports iteration.
  • start -- The subscript starting position.
season=['spring','summer','fall','winter']
print(enumerate(season))
# 输出 <enumerate object at 0x000002CE4C2EC870>
print(list(enumerate(season)))
# 输出 [(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')]
for i in enumerate(season):
    print(i)
# 输出 (0, 'spring')
#      (1, 'summer')
#      (2, 'fall')
#      (3, 'winter')
for i,element in enumerate(season):
    print(i,season[i])
    print(i)
#输出 0 spring
#     0
#     1 summer
#     1
#     2 fall
#     2
#     3 winter
#     3
abc='abcdefg'
print(enumerate(abc))
print(list(enumerate(abc)))
for i in enumerate(abc):
    print(i)
for i,element in enumerate(abc):
    print(i,abc[i])

# output: 

<enumerate object at 0x000001B75A712828>
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')]
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
(5, 'f')
(6, 'g')
0 a
1 b
2 c
3 d
4 e
5 f
6 g

13.  defaultdict(int) function 

    defaultdict is a subclass of dict. Usually, the data type of dictionary (dict) in Python is accessed through key-value pairs. When a key that does not exist is indexed, a keyerror exception will be raised. Then, defaultdict can solve this problem, it can be implemented to return a default value for the key value that does not exist.

    defaultdict is a module under the collections package. Defaultdict can provide a default_factory parameter during initialization. default_factory receives a factory function as a parameter, which can be a built-in function such as int, str, list, etc., or a custom function.

  • defaultdict(int) : initialized to 0
  • defaultdict(float) : initialized to 0.0
  • defaultdict(str) : initialized to ''
# ① 统计字符串中字母出现的个数

from collections import defaultdict
s = 'mississippi'
d = defaultdict(int)
for k in s:
    d[k] += 1
print(d)
# 输出
# defaultdict(<class 'int'>, {'m': 1, 'i': 4, 's': 4, 'p': 2})

#如果不用 defaultdict 的话,写法如下:
s = 'mississippi'
d = {}
for k in s:
    if k not in d:
        d[k] = 1
    else:
        d[k] = d[k] + 1
print(d)
# 输出
# {'m': 1, 'i': 4, 's': 4, 'p': 2}

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)
print(d)
# 输出
# defaultdict(<class 'list'>, {'yellow': [1, 3], 'blue': [2, 4], 'red': [1]})

# ② 使用 lambda 函数。
q = defaultdict(lambda: [0, 0, 0])
print(q['a'])
# 输出
# [0, 0, 0]

14.  bisect.insort, bisect.bisect function  

bisect is a Python built-in module for insertion and lookup of ordered sequences.

bisect.insort (seq, item) inserts the variable item into the sequence seq, and can maintain the ascending order of seq.

bisect.bisect(a,c) : returns the index value of the last <=c in the array a + 1

If c exists in array a, bisect.bisect_left(a,c) returns the index value of the first occurrence of c in array a

If c does not exist in array a, bisect.bisect_left is equivalent to bisect.bisect

If c exists in array a, bisect.bisect_right(a,c) returns the last index value equal to c in array a + 1

If c does not exist in array a, bisect.bisect_right is equivalent to bisect.bisect

import bisect
import random
 
SIZE = 7
random.seed(1729)
my_list = []
for i in range(SIZE):
    new_item = random.randrange(SIZE * 2)
    bisect.insort(my_list, new_item)
    print('%2d ->' % new_item, my_list)
# 输出结果为:
'''
10 -> [10]
 0 -> [0, 10]
 6 -> [0, 6, 10]
 8 -> [0, 6, 8, 10]
 7 -> [0, 6, 7, 8, 10]
 2 -> [0, 2, 6, 7, 8, 10]
10 -> [0, 2, 6, 7, 8, 10, 10]
'''

Guess you like

Origin blog.csdn.net/baidu_41774120/article/details/130280196