List of operations

1 List merge

   Without for loop, you can directly use + or extend method

    a=[1,2,3];b=[4,5,6]

    a+b

    Or a.extend(b)

   [1,2,3,4,5,6]

  If the list is large, + will be slower, and extend is better

2 Deduplication of list elements

   Use set() to de-duplicate list elements

  a=[1,2,3,4,2,3]

  list(set(a))

3 List sorting

  Use sort or the built-in function sorted to sort the list. There are two differences between them:

   a sort () method is to operate on the original list, and the sorted () method will return a new list

   b sort() is a method on the application list, and sorted() can sort all iterable objects

 

   The default is ascending order, it can be changed to descending order

   a.sort(reverse=True) #Descending order

 4 Traverse the index and element pairs of the list

   Use enumerate() function to output index and element value at the same time

 a=["python","study"]

for  i ,v  in  enumerate(a):

     print (i, v)

5 Find the most frequently occurring element in the list

 Use the max() function to quickly find the most frequently occurring element in a list

 b=max(set(a),key=a.count)

6 Count the number of occurrences of all elements in the list

   If you want to know the number of occurrences of all elements in the list, you can use the collections module. The collections module is a treasure module in python, which provides a lot of operation methods for sequences.

The counter method can perfectly solve this demand. Counter returns a dictionary

import random
import collections
lista=[]
for i in range(15):
    lista.append(random.randint(1,10))

print(lista)
dicta=dict(collections.Counter(lista))
print(dicta)


#结果
[1, 6, 7, 1, 2, 1, 9, 7, 4, 5, 7, 10, 6, 5, 5]
{1: 3, 6: 2, 7: 3, 2: 1, 9: 1, 4: 1, 5: 3, 10: 1}

 

7 Combine the two lists into a dictionary

  a=[1,2,3]

  b=["one","two","three"]

 dict(zip(a,b))

{1:"one",2:"two",3:"three"}

 

8 Remove a minimum and a maximum operation

a=[4,5,6,1]

minx,*mid,maxx=sorted(a)

print(mid)

[4,5]

Calculate the average sum(mid)/len(mid)

4.5

9 Ignore point model elements (implemented with underscore)

a=[4,5,6,1]

minx,_,*mid,maxx=sorted(a)

Ignore the second smallest element

print(mid)      ====>5

 

 

Guess you like

Origin blog.csdn.net/sichuanpb/article/details/114866664