Python basic convenience operation

python convenience

list comprehension

Usually we generate a list:

def fun(x):
    return x ** 2
l = []
for i in range(5):
    l.append(fun(i))

It can actually be simplified with a list comprehension:[* for i in *]

[fun(i) for i in range(5)]

At the same time, list comprehensions also support multiple levels of nesting:

In:	[m + '_' + n for m in ['a','b'] for n in ['v','e']]
Out:['a_v', 'a_e', 'b_v', 'b_e']

conditional assignment

To give an example, truncate the elements in the list that exceed 5, that is, those that exceed 5 are replaced by 5, and those that are less than 5 retain the original value:

In:		L = [1, 2, 3, 4, 5, 6, 7]
		[i if i <= 5 else 5 for i in L]
Out:	[1, 2, 3, 4, 5, 5, 5]

Anonymous function and map method

The definition of a function generally has a clear mapping relationship, and we can express it concisely in the form of an anonymous function

fun = lambda x : x ** 2

But obviously we have violated the meaning of "anonymous". In many cases, we don't need to call a function in multiple places, so we often don't care about the name of the function, but only care about the mapping relationship of the function.

(lambda x: x ** 2)(8)
[(lambda x: x ** 2)(i) for i in range(5)]

And the above-mentioned anonymous function mapping of list comprehension, we use the map function to achieve. map returns a map object, which needs to be converted into a list by list

list(map(lambda x, y:str(x)+"_"+y,range(5),list('abcde')))

zip object and enumerate method

  • The zip function can pack multiple iterable objects into an iterable object composed of tuples, and it returns a zip object, and the corresponding packaging results can be obtained through tuple and list
l1 = ('avd')
l2 = ('efsf')
list(zip(l1,l2))
[('a', 'e'), ('v', 'f'), ('d', 's')]
for i,v in zip(range(len(l)),l):
    print(i,' ',v,)
0   a
1   v
2   r
3   d
  • enumerate is a special package that can bind the traversal sequence number of the iterated element when iterating
l = list('avrd')
for i, v in enumerate(l):
    print(i,v)
0   a
1   v
2   r
3   d

Guess you like

Origin blog.csdn.net/weixin_64632836/article/details/127695584