current position:Home>Python lists, dictionaries, tuples, collections, learning notes

Python lists, dictionaries, tuples, collections, learning notes

2022-02-02 06:32:27 Operation and maintenance development story

WeChat official account : O & M development story , author :wanger

Column surface
List in python There are ordered collection object types .
The object in the list can be any object : Numbers , character string , Lists or dictionaries , Tuples . Unlike strings , Lists are mutable objects , Support original modification
python The list is :

  • An ordered set of arbitrary objects

  • Read by offset

  • Variable length 、 Heterogeneous and arbitrarily nested

  • A group belonging to a variable sequence

  • Object reference array

List operation

The operation of the list and the string are mostly the same :
Merge / repeat :

  • list1+list2: The result is that the two lists are combined in order

  • list*3: The result is a list list Repeat three times

  • for i in list1: print(i): Print the contents of the list in order

  • 3 in list: Determine whether an object in the list is an object 3

  • list1.index(1): The first one in the search list is 1 The location of the object

  • list1.count(1): The object in the search list is 1 The number of

  • list1[x:y]: Take the first place x To y The object of , Rebuild a list

  • len(list1):list1 Number of objects in

Basic list operation
  • Create a list :
>>> list=[]
>>> list=[1,2,'3',[]]
>>> list
[1, 2, '3', []]
 Copy code 
  • List value :
>>> list[1]
2
>>> list[0:3]
[1, 2, '3']
 Copy code 
  • Duplicate list content :
>>> list*3
[1, 2, '3', [], 1, 2, '3', [], 1, 2, '3', []]
 Copy code 
  • Use in Method to determine whether the object is in the list :
>>> 3 in listFalse
>>> [] in list
True
 Copy code 
  • Loop printing :
>>> for i in list:
...     print (i,end=' ')
...1 2 3 []
 Copy code 
  • Create the list iteratively :
>>> list=[i*4 for i in 'ASDF' ]
>>> list
['AAAA', 'SSSS', 'DDDD', 'FFFF']
 Copy code 
  • matrix :
list=[ [1,2,3,],[4,5,6],[7,8,9] ]
>>> list
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> list[0][1]
2
>>> list[1][2]
6
 Copy code 
  • Modify the list as it is :
>>> food=['spam','eggs','milk']
>>> food[1]'eggs'
>>> food[1]='Eggs'
>>> food[:]
['spam', 'Eggs', 'milk']
 Copy code 
List method
  • Add list :
>>>food.append('cake')  
>>> food
['spam', 'Eggs', 'milk', 'cake']
 Copy code 
  • Sort the list :
>>> food.sort()    
>>> food
['Eggs', 'cake', 'milk', 'spam']
 Copy code 
  • Merge list :
>>> list1=[1,2,3]
>>> list2=[4,5,6]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6]
 Copy code 
  • Value of the list :
>>> list1.pop()
6
>>> list1
[1, 2, 3, 4, 5]
 Copy code 
  • The list is displayed in reverse order :
>>> list1
[1, 2, 3, 4, 5]
>>> list1.reverse()
>>> list1
[5, 4, 3, 2, 1]
 Copy code 
  • Index of the list :
>>> list=[1,2,3,4,5]
>>> list.index(3)
2
 Copy code 
  • Insertion of list :
>>> list.insert(2,10)
>>> list
[1, 2, 10, 3, 4, 5]
 Copy code 
  • Delete an object in the list :
>>> list
[1, 2, 10, 3, 4, 5]
>>> del list[2]
>>> list
[1, 2, 3, 4, 5]
 Copy code 
  • Sort the list :
    By default, the sorting of lists is based on the case of letters , You can add an option to the list key=lower.str Convert them all to lowercase , Use reverse=True In reverse order
>>> list=['abc','aDd','ace']
>>> sorted(list)
['aDd', 'abc', 'ace']
>>> list
['abc', 'aDd', 'ace']
>>> sorted(list,key=str.lower,reverse=True)
['aDd', 'ace', 'abc']
>>> sorted(list,key=str.lower)
['abc', 'ace', 'aDd']
>>>sorted([x.lower() for x in list])
['abc', 'ace', 'add']
>>> sorted([x.lower() for x in list],reverse=True)
['add', 'ace', 'abc']
 Copy code 
The actual use of lists
  • Value :
>>> info=['myname',18,[1997,9,28]]
>>> _name,_age,_birth=info
>>> _name'myname'
>>> _age
18
>>> _birth
[1997, 9, 28]
>>> _name,_age,(_birth_y,_birth_m,_birth_d)=info
>>> _birth_y
1997
>>> _birth_m,_birth_d
(9, 28)
 Copy code 

When the value is not fixed , It can be used * Instead of :

>>> a=['adc',122,2215,'[email protected]']
>>> a_name,*a_phone,a_mail=a
>>> a_name
'adc'
>>> a_phone
[122, 2215]
 Copy code 
  • Keep only the last... In the list N Elements :
    Use deque Function can set the number of elements in the list , If the maximum limit of the list is exceeded , Then the leftmost element in the list will be deleted , If it is added on the left , Then the rightmost element is deleted
>>> from collections import deque
>>> q=deque(maxlen=3)
>>> q.append(1)
>>> q.append(2)
>>> q.append(3)
>>> q
deque([1, 2, 3], maxlen=3)
>>> q.append(4)
>>> q
deque([2, 3, 4], maxlen=3) 
>>> q.appendleft('5')
>>> q
deque(['5', 2, 3], maxlen=3)
 Copy code 
  • Take out the maximum and minimum values in the list :
    Use heapq Modular nlargest,nsmallest Method to get several maximum and minimum values in the list , You can also use it max and min Function to find the maximum and minimum , Use sum Function to find the sum of list numbers
>>> from heapq import nlargest,nsmallest
>>> num=[1,4,6,7,8,8,34,64,23,7,45,34]
>>> nlargest(3,num)
[64, 45, 34]
>>> nlargest(2,num)
[64, 45]
>>> nsmallest(2,num)
[1, 4]
>>> nsmallest(4,num)
[1, 4, 6, 7]
>>> num
[1, 4, 6, 7, 8, 8, 34, 64, 23, 7, 45, 34]
>>> max(num)
64
>>> min(num)
1
>>> sum(num)
241
>>> a_info=['wanger','wangerxiao',25,'computer']
>>> _name=slice(0,2)
>>> _age=slice(2,3)
>>> _job=slice(3,4)
>>> a_info[_name]
['wanger', 'wangerxiao']
>>> a_info[_age]
[25]
>>> a_info[_job]
['computer']
 Copy code 
  • Repeat element calculation :
    It uses collections Modular Counter Method
>> a=[1,2,3,4,5,6,2,4,2,5,6]
>>> from collections import Counter
>>> count_word=Counter(a)
>>> count_word
Counter({2: 3, 4: 2, 5: 2, 6: 2, 1: 1, 3: 1})
>>> count_word.most_common(3)
[(2, 3), (4, 2), (5, 2)]
>>> count_word.most_common(2)
[(2, 3), (4, 2)]
 Copy code 

Dictionaries

The dictionary is python There are unordered collection object types .
Dictionary values have separate and unique keys , Use the corresponding key to get the value .
python The main features of the dictionary are as follows :

  • Read by key instead of offset

  • An unordered combination of arbitrary objects

  • Variable length , isomerism , Any nesting

  • It belongs to mappable type

  • Object reference table

Dictionary usage precautions :

  • Invalid sequence operation —— Series connection , Slices cannot be used

  • For the new index ( key ) The assignment adds an item

  • Keys don't have to be strings —— As long as it is an immutable object ( Except list Dictionary )

Basic operation of dictionary :

  • Dictionary assignment :
>>> dict={'a':97,'b':98}
>>> len(dict)
2
>>> print("ascii code of 'a' is {},ascii code of 'b' is {}".format(dict['a'],dict['b']))
ascii code of 'a' is 97,ascii code of 'b' is 98
 Copy code 
  • Determine whether a particular key exists in the dictionary :
>>> 'a' in dict
True
>>> 'b
>>>> 'b' is in dict
True
 Copy code 
  • Place to modify :
# Change the value of a specific key 
>>> food={'eggs':3,'ham':1,'spam':4}
>>> food['ham']=2
>>> food
{'eggs': 3, 'ham': 2, 'spam': 4}
# Add new keys and corresponding values 
>>> food['branch']=['bacon','bake']
>>> food
{'eggs': 3, 'ham': 2, 'spam': 4, 'branch': ['bacon', 'bake']}
# Delete a dictionary element 
>>> del food['eggs']
>>> food
{'ham': 2, 'spam': 4, 'branch': ['bacon', 'bake']}
# Empty all dictionary entries 
>>> dict.clear()
# Delete Dictionary 
del dict
 Copy code 

Dictionary method

  • Find out whether the key value of the dictionary exists , If it does not exist, you can set the returned value
>>> food.get('ham')
2
>>> dict.get('b')
2
>>> dict.get('0')
>>> dict.get('0','none')
'none'
 Copy code 
  • How to create a dictionary :
    1. The most primitive method :
dict={'name':'wanger','age':25}
 Copy code 

       2. Key assignment method :

>>> dict={}
>>> dict['name']='wanger'
>>> dict['age']=25
 Copy code 
  • Dictionary comparison :
    Dictionary comparison will compare dictionary keys , Not the value of the dictionary , have access to zip The method reverses the dictionary values and keys , This will compare the value , have access to sorted Function to sort the dictionary
>>> dict={'a':1,'b':2,'c':3,'d':4}
>>> max(dict)
'd'
>>> min(dict)
'a'
>>> max(zip(dict.values(),dict.keys()))
(4, 'd')
>>> min(zip(dict.values(),dict.keys()))
(1, 'a')
>>> sorted(zip(dict.values(),dict.keys()))
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
>>> sorted(zip(dict.values(),dict.keys()),reverse=True)
[(4, 'd'), (3, 'c'), (2, 'b'), (1, 'a')]
 Copy code 
  • Sort dictionary list :
    have access to sorted Function to sort , Use key Parameter can define the sorting key , We need to use operator Modular itemgetter function
>>> rows
[{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, 
{'fname': 'John', 'lname': 'Clesse', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}]
>>> from operator import itemgetter
>>> rows_fname=sorted(rows,key=itemgetter('fname'))
>>> rows_fname
[{'fname': 'Big', 'lname': 'Jones', 'uid': 1004},
{'fname': 'Brian', 'lname':'Jones', 'uid': 1003}, 
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, 
{'fname': 'John', 'lname': 'Clesse', 'uid': 1001}]
>>> rows_uid=sorted(rows,key=itemgetter('uid'))
>>> rows_uid
[{'fname': 'John', 'lname': 'Clesse', 'uid': 1001}, 
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002}, 
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}]
 Copy code 

Tuples

Tuple Introduction

Tuples are very similar to lists , It just can't be changed in place , Yuan Zu Zai python The characteristics of :

  • An ordered combination of arbitrary objects

  • Get data by offset

  • It belongs to the immutable sequence type

  • Fixed length , isomerism , Any nesting

  • Object reference array

Tuple creation

Yuanzu created when there was only a single element , You have to add a comma (,), Tuples can be nested in tuples

>>> tuple=()
>>> tuple=(1,)
>>> type(tuple)
<class 'tuple'>
# It's the same with or without parentheses 
>>> tuple=(1,2,'3',(4,5))
>>> tuple
(1, 2, '3', (4, 5))
>>> tuple=1,2,'3',(4,5)
>>> tuple
(1, 2, '3', (4, 5))
 Copy code 

Convert list to tuple

>>> list=[1,2,3,4]
>>> sd=tuple(list)
>>> sd
(1, 2, 3, 4)
 Copy code 

Tuple method

  • Sorting tuples :
    Tuples pass through sorted After ordering , It will be converted to a list
>>> tuple=(1,5,3,6,4,2)
>>> sorted(tuple)
[1, 2, 3, 4, 5, 6]
 Copy code 
  • Find tuple element location :
>>> tuple
(1, 5, 3, 6, 4, 2)
>>> tuple.index(3)
2
 Copy code 
  • Calculate the number of tuple elements :
>>> tuple
(1, 5, 3, 6, 4, 2)
>>> tuple.count(3)
1
 Copy code 
  • Slice of tuple :
>>> tuple[0]
1
>>> tuple[2:]
(3, 6, 4, 2)
>>> tuple[2:3]
(3,)
 Copy code 
  • The operation of lists and tuples is similar , In the list operation, as long as it is not modified in place , Can be used for tuples
>>> (1,2)+(3,4)
(1, 2, 3, 4)
>>> (1,2)*4
(1, 2, 1, 2, 1, 2, 1, 2)
>>> len(tuple)
 Copy code 

aggregate

Collection Introduction

set Is an unordered and unrepeatable set of elements
A collection object is an unordered set of hashable values , Collection members can be keys in the dictionary .set Also support with in and not in Operator check member , Because the set itself is out of order , You cannot create indexes or slice collections , There is also no key to get the value of the element in the collection .

Set features

  • The elements in the collection are the same as the keys in the dictionary

  • The elements in the collection are immutable objects

Set creation

>>> s=set('a')
>>> a=set({'k1':1,'k2':2})
>>> b=(['y','e','d','o'])
>>> c={'a','b','c'}
>>> d={('a','b','c')}
 Copy code 

Set basic operations

  • Comparison of sets
# Compare a、b Collection a in ,b Collection that does not exist in 
>>> a={11,22,33}
>>> b={11,23,45}
>>> a.difference(b)
{33, 22}
# find a in ,b Collection that does not exist in , And put a、b All values in the set are overwritten 
>>> a={11,22,33}
>>> print(a.difference_update(b))
None
>>> a
{33, 22}
 Copy code 
  • Delete of collection :
>>> a={11,22,33}
>>> a.discard(11)
>>> a.discard(44)
>>> a
{33, 22}
# Removing non-existent elements will report an error 
>>> a={11,22,33}
>>> a.remove(11)
>>> a.remove(44)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 44
>>> a
{33, 22}
# Remove the end element 
>>> a={11,22,33}
>>> a.pop()
33
>>> a
{11, 22}
 Copy code 
  • intersect :
# Take the intersection and assign it to the new value 
>>> a={1,2,3,4}
>>> b={6,5,4,3}
>>> print (a.intersection(b))
{3, 4}
# Take the intersection and assign it to a
>>> print (a.intersection_update(b))
None
>>> a
{3, 4}
 Copy code 
  • Set judgment :
>>> a={3,4}
>>> b={6,5,4,3}
# Judge a Whether or not b There is no intersection , There is intersection False, No intersection True
>>> a.isdisjoint(b)
False
# Judge a Whether it is b Subset 
>>> a.issubset(b)
True
# Judge a Whether it is b A set of parent 
>>> a.issuperset(b)
False
 Copy code 
  • Set merge :
>>> a={1,2,3,4}
>>> b={3, 4, 5, 6}
# Print different elements 
>>> print (a.symmetric_difference(b))
{1, 2, 5, 6}
# Print different elements , And overwrite the set a
>>> print (a.symmetric_difference_update(b))
None
>>> a
{1, 2, 5, 6}
 Copy code 
  • Set takes Union :
>>> a={1, 2, 5, 6}
>>> b={3, 4, 5, 6}
>>> print (a.union(b))
{1, 2, 3, 4, 5, 6}
 Copy code 
  • Update of collection :
>>> a={1, 2, 5, 6}
>>> b={3, 4, 5, 6}
# hold a、b Merge the values of , And assign the value to the set a
>>> a.update(b)
>>> a
{1, 2, 3, 4, 5, 6}
# add to a Elements of the set 
>>> a.update([7,8])
>>> a
{1, 2, 3, 4, 5, 6, 7, 8}
 Copy code 
  • The transformation of sets :
    Convert sets to lists respectively 、 Tuples 、 character string
>>> a=set(range(5))>>> li=list(a)
>>> tu=tuple(a)
>>> st=str(a)
>>> print (li)
[0, 1, 2, 3, 4]
>>> print (tu)
(0, 1, 2, 3, 4)
>>> print (st)
{0, 1, 2, 3, 4}

 Copy code 

This article USES the Article synchronization assistant Sync

copyright notice
author[Operation and maintenance development story],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020632256215.html

Random recommended