Python built-in data structures list, set, dict and tuple (III)

Time:2021-10-16

Functions on tuples

  • Here’s the code
  • The following functions are basically applicable to list
#Len: get the length of the tuple
t = (1,2,3,4,5)
len(t)
5



#Max, Min: maximum and minimum
print(max(t))
print(min(t))
5
1


#Tuple: convert or create tuples
l = (1,2,3,4,5)
t = tuple(l)
print(t)

t = tuple()
print(t)
(1, 2, 3, 4, 5)
()

Tuple function

  • Basically common with list
#Count: calculates the number of occurrences of the specified data
t = (2,1,2,3,45,1,1,2,)

print(t.count(2))

#Index: find the index position of the specified element in the tuple

print(t.index(45))
#If you need to find more than one number, the first one is returned

print(t.index(1))
3
4
1

Tuple variable exchange method

  • Two variables exchange values
#Two variables exchange values
a = 1
b = 3

print(a)
print(b)
print("*" * 20)
#Java programmers would write this:
c = a
a = b
b = c
print(a)
print(b)

print("*" * 20)
#Python writing
a,b = b,a
print(a)
print(b)
1
3
********************
3
1
********************
1
3

Set set

  • Set is a concept in high school mathematics
  • A certain set of unordered unique data, and each data in the set becomes an element
#Definition of set
s = set()
print(type(s))
print(s)

#At this time, there must be a value in braces, otherwise a dict is defined
s = {1,2,3,4,5,6,7}
print(type(s))
print(s)
<class 'set'>
set()
<class 'set'>
{1, 2, 3, 4, 5, 6, 7}


#If it is only defined in curly braces, a dict type is defined
d = {}
print(type(d))
print(d)
<class 'dict'>
{}

Characteristics of sets

  • The data of the collection is out of order, that is, indexes and shards cannot be used
  • The internal data elements of the collection are unique and can be used to exclude duplicate data
  • The data in the set, STR, int, float, tuple, frozen set, etc., that is, only hashable data can be placed inside

Set sequence operation

#Member detection
# in,not in
s = {4,5,"i", "love", "you"}
print(s)

if "love" in s:
    print("Yes")
    
if "haha" not in s:
    print("Yes")
{'you', 4, 5, 'love', 'i'}
Yes
Yes

Collection traversal operation

#For loop
s = {4,5,"i", "love", "you"}

for i in s:
    print(i)
you
4
5
love
i


#Collection traversal with tuples
s = {(1,2,3,), ("i", "love", "you"), (4,5,6)}

for k,m,n in s:
    print(k, "--", m, "--", n)
    
for k in s:
    print(k)
i -- love -- you
4 -- 5 -- 6
1 -- 2 -- 3
('i', 'love', 'you')
(4, 5, 6)
(1, 2, 3)

Connotation of set

#General set connotation
#The following sets automatically filter out duplicate elements after initialization
s = {23,223,233,2,4,5,6,3,4,1,5,3}
print(s)

#General set connotation
ss = {i for i in s}
print(ss)
{1, 2, 3, 4, 5, 6, 233, 23, 223}
{1, 2, 3, 4, 5, 6, 233, 23, 223}


#Conditional set connotation
sss = {i for i in s if i % 2 == 0}
print(sss)
{2, 4, 6}


#Set connotation of multi cycle
s1 = {1,2,3,4}
s2 = {"i", "love", "you"}

s = {m*n for m in s2 for n in s1}
print(s)

s = {m*n for m in s2 for n in s1 if n == 2}
print(s)
{'you', 'youyou', 'love', 'lovelovelovelove', 'lovelovelove', 'lovelove', 'iii', 'youyouyouyou', 'ii', 'i', 'iiii', 'youyouyou'}
{'lovelove', 'youyou', 'ii'}

Set functions / functions about sets

#Len, Max, Min: consistent with other basic functions
s = {23,54,72,3,5,3,3,6,1,543}
print(len(s))
print(max(s))
print(min(s))
8
543
1


#Set: generate a set
l = {1,2,3,4,5,4,3,2,1}
s = set(l)
print(s)
{1, 2, 3, 4, 5}


#Add: adds an element to the collection
s = {1}
s.add(3)
print(s)
{1, 3}


# clear
s = {1,2,3,4,5}
print(id(s))
s.clear()
print(id(s))
#The results show that the clear function empties the data in place
1370773843528
1370773843528


#Copy: copy
#Remove: remove the specified value and directly change the original value. If the value to be deleted does not exist, an error will be reported
#Discard: the value specified in the removal set is the same as remove, but if you want to delete it, no error will be reported
s = {23,4,3,5,1,2,3}
s.remove(4)
print(s)
s.discard(1)
print(s)

print("*" * 20)
s.discard(100)
print(s)

s.remove(100)
print(s)
{1, 2, 3, 5, 23}
{2, 3, 5, 23}
********************
{2, 3, 5, 23}



---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-35-0113522ad176> in <module>
     12 print(s)
     13 
---> 14 s.remove(100)
     15 print(s)


KeyError: 100


#Pop randomly removes an element
s = {1,2,3,4,5,6,7}
d = s.pop()
print(d)
print(s)
1
{2, 3, 4, 5, 6, 7}


#Set function
#Intersection: intersection
#Difference: difference set
#Union: Union
#Issubset: check whether a set is another subset
#Issuperset: checks whether a set is another superset
s1 = {1,2,3,4,5,6}
s2 = {5,6,7,8,9}

s_1 = s1.intersection(s2)
print(s_1)

s_2 = s1.difference(s2)
print(s_2)

s_3 = s1.issubset(s2)
print(s_3)

s_4 = s1.issuperset(s2)
print(s_4)
{5, 6}
{1, 2, 3, 4}
False
False


#Set mathematical operation
s1 = {1,2,3,4,5,6}
s2 = {5,6,7,8,9}

#The following are not supported
s_1 = s1 - s2
print(s_1)

s_2 = s1 + s2
print(s_2)
{1, 2, 3, 4}



---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-45-fac787d752ea> in <module>
      7 print(s_1)
      8 
----> 9 s_2 = s1 + s2
     10 print(s_2)


TypeError: unsupported operand type(s) for +: 'set' and 'set'

Frozen set: Frozen set

  • Freezing means that no modification can be made
  • Frozenset is a special set
#Create
s = frozenset()
print(type(s))
print(s)
<class 'frozenset'>
frozenset()

Dict dictionary

  • Dictionary is a kind of combined data. There is no sequential combined data. The data appears in the form of key value pairs
#Dictionary creation
#Create empty dictionary 1
d = {}
print(type(d))
print(d)

#Create empty dictionary 2
d = dict()
print(d)

#Create a dictionary with values. Each set of data is separated by colons and each pair of key value pairs is separated by commas
d = {"one":1, "two":2, "three":3}
print(d)

#Creating content dictionary with dict 1
d = dict({"one":1, "two":2, "three":3})
print(d)

#Creating dictionary with dict 2
#Use key parameters
d = dict(one=1, two=2, three=3)
print(d)

# 
d = dict( [("one",1), ("two",2), ("three",3)])
print(d)
<class 'dict'>
{}
{}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}
{'one': 1, 'two': 2, 'three': 3}


Characteristics of dictionary

  • The dictionary is a sequence type, but it is an unordered sequence, so there is no fragmentation and index
  • Each data in the dictionary consists of key value pairs, namely kV pairs

    • Key: must be hashable values, such as int, string, float, tuple, but not list, set, dict
    • Value: any value

Common operations of dictionary

#Access data
d = {"one":1, "two":2, "three":3}
#Note access format
#Key values are in brackets
print(d["one"])

d["one"] = "eins"
print(d)

#Delete an operation
#Using del operations
del d["one"]
print(d)
1
{'one': 'eins', 'two': 2, 'three': 3}
{'two': 2, 'three': 3}


#Member detection: in, not in
#Key content during member detection
d = {"one":1, "two":2, "three":3}

if 2 in d:
    print("value")

if "two" in d:
    print("key")
    
if ("two,2") in d:
    print("kv")
key


#Traversal is quite different between python2 and 3, and the code is not general
#Use for loop by key value
d = {"one":1, "two":2, "three":3}
#Use the for loop to access directly by keu value
for k in d:
    print(k, d[k])
    
#The above code can be rewritten as follows
for k in d.keys():
    print(k, d[k])

#Access only dictionary values
for v in d.values():
    print(v)
    
#Note the following special usage
for k,v in d.items():
    print(k, "--", v)
one 1
two 2
three 3
one 1
two 2
three 3
1
2
3
one -- 1
two -- 2
three -- 3

Dictionary generator

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

#General dictionary generator
dd = {k:v for k,v in d.items()}
print(dd)

#Dictionary generation with constraints
dd = {k:v for k,v in d.items() if v % 2 == 0}
print(dd)
{'one': 1, 'two': 2, 'three': 3}
{'two': 2}

Dictionary correlation function

#General functions: len, Max, min, Dict
#Str (Dictionary): the string format used to return the dictionary
d = {"one":1, "two":2, "three":3}
print(str(d))
{'one': 1, 'two': 2, 'three': 3}


#Clear: clear the dictionary
#Items: returns the tuple format composed of key value pairs of the dictionary

d = {"one":1, "two":2, "three":3}
i = d.items()
print(type(i))
print(i)
<class 'dict_items'>
dict_items([('one', 1), ('two', 2), ('three', 3)])


#Keys: a structure that returns the keys of the dictionary
k = d.keys()
print(type(k))
print(k)
<class 'dict_keys'>
dict_keys(['one', 'two', 'three'])


#Values: similarly, an iterative structure
v = d.values()
print(type(v))
print(v)
<class 'dict_values'>
dict_values([1, 2, 3])


#Get: returns the corresponding value according to the specified key. The advantage is that the default value can be generated

d = {"one":1, "two":2, "three":3}
print(d.get("oner"))

#The default value of get is none, which can be set
print(d.get("one", 100))
print(d.get("one33", 100))

print(d['on333'])
None
1
100



---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-86-f8c01a58018e> in <module>
      8 print(d.get("one33", 100))
      9 
---> 10 print(d['on333'])


KeyError: 'on333'


#From keys: use the specified sequence as the key and a value as the value of all keys in the dictionary
l = ["eins", "zwei", "dree"]
#Note the type of the fromkeys two parameters
#Notice the calling body of fromkeys
d = dict.fromkeys(l, "hahahahaha")
print(d)
{'eins': 'hahahahaha', 'zwei': 'hahahahaha', 'dree': 'hahahahaha'}