Python common data structure collation

Python common data structure arrangement#

1. Sequence (list, tuple and string)

The following focuses on lists, tuples and strings.

1、 List###

(1), create

list1=['hello','world']
print list1
list2=[1,2,3]
print list2

Output:
[' hello', 'world']
[1, 2, 3]

As you can see, the creation method here is very similar to the array in javascript.

(2), list function####

It is very effective to create a list of strings through the list function (in fact, list is a type rather than a function):

list3=list("hello")
print list3

Output:
[' h', 'e', 'l', 'l', 'o']

2、 Tuple###

(1), create

t1=1,2,3
t2="jeffreyzhao","cnblogs"
t3=(1,2,3,4)
t4=()
t5=(1,)
print t1,t2,t3,t4,t5

Output:
(1, 2, 3) (' jeffreyzhao', 'cnblogs') (1, 2, 3, 4) () (1,)

From the above analysis, we can get:
a. Comma separated some values, the tuple is automatically created;
b. Tuples are enclosed by parentheses most of the time;
c. Empty tuples can be represented by parentheses without any content;
d. Tuples containing only one value must add a comma (,);

(2), tuple function

The tuple function is almost the same as the list function of a sequence: it takes a sequence (note the sequence) as a parameter and converts it to a tuple.

If the parameter is a tuple, then the parameter will be returned as is:

t1=tuple([1,2,3])
t2=tuple("jeff")
t3=tuple((1,2,3))
print t1
print t2
print t3
t4=tuple(123)
print t4

Output:
(1, 2, 3)
(' j', 'e', 'f', 'f')
(1, 2, 3)
Traceback (most recent call last):

File "F:\Python\test.py", line 7, in

t4=tuple(123)

TypeError: 'int' object is not iterable

3、 String###

(1) Create

str1='Hello world'
print str1
print str1[0]for c in str1:
 print c

Output:
Hello world
H
H
e
l
l
o

w
o
r
l
d

(2) Format

str1='Hello,%s'%'world.'
print str1
strs=('Hello','world') #Tuple
str1='%s,%s'% strs
print str1
d={'h':'Hello','w':'World'} #dictionary
str1='%(h)s,%(w)s'% d
print str1

Output:

Hello,world
Hello,World

str1='%s,%s'%'Hello','world'
print str1

Output:

Traceback (most recent call last):

File "F:\Python\test.py", line 2, in

str1='%s,%s'%'Hello','world'

TypeError: not enough arguments for format string

str1='%s%%'%100

print str1

Output: 100%

from math import pi
str1='%.2f'% pi #Accuracy 2
print str1
str1='%10f'% pi #Field width 10
print str1
str1='%10.2f'% pi #Field width 10, precision 2
print str1

Output:

3.14

3.141593

3.14

String formatting also contains many other rich conversion types, please refer to official documents.

It works similarly to variable substitution in many UNIX Shells, as shown below:

from string import Template

str1=Template('$x,$y!')

str1=str1.substitute(x='Hello',y='world')

print str1

Output:

Hello,world!

from string import Template

str1=Template('Hello,w${x}d!')

str1=str1.substitute(x='orl')

print str1

Output:

Hello,world!

from string import Template

str1=Template('$x$$')

str1=str1.substitute(x='100')

print str1

Output: 100$

from string import Template

d={'h':'Hello','w':'world'}

str1=Template('$h,$w!')

str1=str1.substitute(d)

print str1

Output:

Hello,world!

In addition to formatting, Python strings also have many built-in practical methods. You can refer to the official documentation, which will not be listed here.

4、 General sequence operation (method)

From lists, tuples, and strings, you can "abstract" some common common methods of sequences (not CRUD as you think),

These operations include: indexing, slicing, adding, multiplying, and checking whether an element is a member of the sequence.

In addition, there are built-in functions for calculating sequence length, maximum and minimum elements, etc.

(1) Index

str1='Hello'

nums=[1,2,3,4]

t1=(123,234,345)

print str1[0]

print nums[1]

print t1[2]

Output

H

2

345

The magic is that the index can start from the last position (from right to left), and the number is -1:

str1='Hello'

nums=[1,2,3,4]

t1=(123,234,345)

print str1[-1]

print nums[-2]

print t1[-3]

Output:

o

3

123

(2) Fragment

Fragmentation operations are used to access elements within a certain range. Fragmentation is achieved by two indexes separated by colons:

nums=range(10)

print nums

print nums[1:5]

print nums[6:10]

print nums[1:]

print nums[-3:-1]

print nums[-3:] #Include the element at the end of the sequence, blank the last index

print nums[:] #Copy the entire sequence

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[1, 2, 3, 4]

[6, 7, 8, 9]

[1, 2, 3, 4, 5, 6, 7, 8, 9]

[7, 8]

[7, 8, 9]

nums=range(10)

print nums

print nums[0:10]  #The default step size is 1 equivalent to nums[1:5:1]

print nums[0:10:2]  #Step size is 2

print nums[0:10:3]  #Step size is 3

## print nums[0:10:0]  #Step size is 0

print nums[0:10:-2]  #The step size is-2

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[0, 2, 4, 6, 8]

[0, 3, 6, 9]

[]

(3) Sequence addition

str1='Hello'

str2=' world'

print str1+str2

num1=[1,2,3]

num2=[2,3,4]

print num1+num2

print str1+num1

Output:

Hello world

[1, 2, 3, 2, 3, 4]

Traceback (most recent call last):

File "F:\Python\test.py", line 7, in

print str1+num1

TypeError: cannot concatenate 'str' and 'list' objects

(4) Multiplication####

print [None]*10

str1='Hello'

print str1*2

num1=[1,2]

print num1*2

print str1*num1

Output:

[ None, None, None, None, None, None, None, None, None, None]

HelloHello

[1, 2, 1, 2]

Traceback (most recent call last):

File "F:\Python\test.py", line 5, in

print str1*num1

TypeError: can't multiply sequence by non-int of type 'list'

(5) Membership (important)

str1='Hello'

print 'h'in str1 

print 'H'in str1

num1=[1,2]

print 1in num1

Output:

False

True

True

(6) Length, maximum and minimum

str1='Hello'

print len(str1) 

print max(str1)

print min(str1)

num1=[1,2,1,4,123]

print len(num1) 

print max(num1)

print min(num1)

Output:

5

o

H

5

123

1

2. Mapping (Dictionary) (Map)

How to create a dictionary and assign values to the dictionary

Simply put, a dictionary is a collection of key-value pairs wrapped in braces. (Key-value pairs are also called items)

adict ={}

adict ={key1:value2, key2:value2, …}

Or use the dict() function, for example, adict = dict() or adict = dict((['x',1],['y',2])) Is it correct?

adict = dict(['x',1],['y',2]). Create a dictionary with keyword parameters, such as: adict= dict(name='allen',age='40')

Or use the fromkeys() method, for example, adict = {}.fromkeys(('x','y'), -1) The value of the dictionary created in this way is the same. If you don't give a value, the default is None.

  1. The key and value are separated by a colon ":";

  2. Item and item are separated by comma ",";

  3. The keys in the dictionary must be unique, and the values need not be unique.

Basic operation of dictionary###

The form adict[key] returns the value corresponding to the key key. If the key is not in the dictionary, a KeyError will be raised.

  1. Add a data item (new element) or key-value pair

adict[new_key] = value form to add an item

  1. Update a data item (element) or key-value pair

adict[old_key] = new_value

  1. Delete a data item (element) or key-value pair

del adict[key] delete the key item / del adict delete the entire dictionary

adict.pop(key) delete the key item and return the value corresponding to the key

Mapping type operator

a. The dictionary does not support splicing and repetition operators (+, *)

b. Dictionary comparison operation

First compare the length of the dictionary, which is the number of elements in the dictionary

Key comparison

Value comparison

example:

adict ={}

bdict ={'name':'allen','age':'40′}cmp(adict, bdict)  #Less than –>-1 is greater than –>1 is equal to –>0

Mapping related functions###

  1. len() returns the length of the dictionary

  2. hash() returns the hash value of the object, which can be used to determine whether an object can be used as a dictionary key

  3. dict() factory function, used to create a dictionary

Dictionary method###

  1. adict.keys() returns a list containing all the keys of the dictionary;

  2. adict.values() returns a list containing all values of the dictionary;

  3. adict.items() returns a list containing all (key, value) primitives;

  4. adict.clear() delete all items or elements in the dictionary;

  5. adict.copy() returns a copy of a shallow copy of the dictionary;

  6. adict.fromkeys(seq, val=None) creates and returns a new dictionary, using the elements in seq as the keys of the dictionary, and val as the initial value corresponding to all keys in the dictionary (the default is None);

  7. adict.get(key, default = None) returns the value corresponding to the key in the dictionary. If the key does not exist in the dictionary, it returns the value of default (default is None by default);

  8. adict.has_key(key) If the key is in the dictionary, return True, otherwise return False. Now use in and not in;

  9. adict.iteritems(), adict.iterkeys(), adict.itervalues() are the same as their corresponding non-iterative methods, the difference is that they return an iterator instead of a list;

  10. adict.pop(key[,default]) is similar to the get method. If the key exists in the dictionary, delete and return the vuale corresponding to the key; if the key does not exist and the default value is not given, a keyerror exception will be raised;

  11. adict.setdefault(key, default=None) is similar to the set() method, but if there is no Key key in the dictionary, adict[key] = default is assigned to it;

  12. adict.update(bdict) Add the key-value pairs of the dictionary bdict to the dictionary adict.

Dictionary traversal###

1、 Traverse the key of the dictionary

for key in adict.keys():print key

2、 Traverse the value of the dictionary

for value in adict.values(): print value

3、 Traverse the items (elements) of the dictionary

for item in adict.items():print item

4、 Traverse the key-value of the dictionary

for item,value in adict.items(): print 'key=%s, value=%s'%(item, value)for item,value in adict.iteritems(): print ‘'key=%s, value=%s'%(item, value)

Note: for item,value in adict.items(): print'key=%s','value=%s', %(item, value) this way of writing is wrong

Notes on using the dictionary###

1、 One key cannot be allowed to correspond to multiple values;

2、 The key must be hashable.

set##

Sets were introduced in Python 2.3 and can usually be created directly using a newer version of Python, as shown below:

strs=set(['jeff','wong','cnblogs'])

nums=set(range(10))
  1. The copy is ignored (members are not duplicated, and duplicates are removed)

The collection is mainly used to check membership, so the copy is ignored. As shown in the following example, the output collection content is the same.

set1=set([0,1,2,3,0,1,2,3,4,5])

print set1

set2=set([0,1,2,3,4,5])

print set2

The output is as follows:

set([0, 1, 2, 3, 4, 5])

set([0, 1, 2, 3, 4, 5])

  1. The order of collection elements is arbitrary

This is very similar to a dictionary. It can be simply understood that the set is a dictionary without a value.

strs=set(['jeff','wong','cnblogs'])

print strs

The output is as follows:

set(['wong', 'cnblogs', 'jeff'])

  1. Common methods of collection

a. Intersection union

set1=set([1,2,3])

set2=set([2,3,4])

set3=set1.union(set2)

print set1

print set2

print set3

Output:

set([1, 2, 3])

set([2, 3, 4])

set([1, 2, 3, 4])

The union operation returns the union of the two sets without changing the original set. Use the bitwise AND (OR) operator "|" to get the same result:

set1=set([1,2,3])

set2=set([2,3,4])

set3=set1|set2

print set1

print set2

print set3

The output is exactly the same as the above union operation.

set1=set([1,2,3])

set2=set([2,3,4])

set3=set1&set2

print set1

print set2

print set3

print set3.issubset(set1)

set4=set1.copy()

print set4

print set4 is set1

The output is as follows:

set([1, 2, 3])

set([2, 3, 4])

set([2, 3])

True

set([1, 2, 3])

False

set1=set([1])

print set1

set1.add(2)

print set1

set1.remove(2)

print set1

print set1

print 29in set1

set1.remove(29) #Remove non-existent item

Output:

set([1])

set([1, 2])

set([1])

set([1])

False

Traceback (most recent call last):

File "F:\Python\test.py", line 9, in

set1.remove(29) #Remove non-existent item

KeyError: 29

Sets are mutable, so they cannot be used as dictionary keys. The collection itself can only contain immutable values, so it cannot contain other collections:

set1=set([1])

set2=set([2])

set1.add(set2)

The output is as follows:

Traceback (most recent call last):

File "F:\Python\test.py", line 3, in

set1.add(set2)

TypeError: unhashable type: 'set'

set1=set([1])

set2=set([2])

set1.add(frozenset(set2))

print set1

Output:

set([1, frozenset([2])])

Recommended Posts

Python common data structure collation
python data structure
Python data structure and algorithm
02. Python data types
Python data model
Python data analysis
Python data format-CSV
Python data analysis-data update
Python data analysis-apply function
Python data analysis-data selection
Python basic data types
Python basic data types
09. Common modules of Python3
Python data analysis-data establishment
Python parsing variable length structure
Python3 crawler data cleaning analysis
Python parses simple XML data
2020--Python grammar common knowledge points
Python Data Science: Logistic Regression
Python Data Science: Regularization Methods
Python Data Science: Related Analysis
Python common exception handling mechanism
Python Data Science: Linear Regression
Python Faker data forgery module
Collection of Python Common Modules
Python Data Science: Chi-Square Test
Python Data Science: Linear Regression Diagnosis
Common errors and solutions in python
Several common modes of Python functions
Python realizes online microblog data visualization
Is python suitable for data mining