Common built-in methods for Python data types

catalogue

Continued 👉 Common built-in methods for Python data types (2)

Common built-in methods for Python data types (3)

1. List built-in method

1. sort(): ascending

  • Collocation parameter: reverse=True # parameter is True, and ascending order changes to descending order

Examples are as follows:

lst = [2, 111, 3, 222, 11, 1, 22, 33, 333]
#Ascending operation
lst.sort()
print(lst)
#Descending operation
lst.sort(reverse=True)
print(lst)

#result
[1, 2, 3, 11, 22, 33, 111, 222, 333]
[333, 222, 111, 33, 22, 11, 3, 2, 1]

2. Reverse(): reverse the order

  • The function is equivalent to a list index step of - 1

Examples are as follows:

lst1 = [1, 2, 3, 4, 5, 6, 7]
# Reverse order
lst1.reverse()
print(lst1)
lst1 = [1, 2, 3, 4, 5, 6, 7]
# The step size of - 1 is equivalent to reverse()
print(lst1[::-1])

#result
[7, 6, 5, 4, 3, 2, 1]
[7, 6, 5, 4, 3, 2, 1]

3. List comparison operation

  • The list comparison operation uses the same index element comparison. As long as there is a comparison result, the program ends

Examples are as follows:

lst2 = [333, 444, 555]
lst3 = [111, 999, 999999, 1, 2, 3]
# Only the first element is compared, 333 > 111, and the program ends
print(lst2 < lst3)

#result
False

2. Dictionary built-in method

python dictionary you deserve!

1. Operation on Key

  • Value by K: if K does not exist, an error will be reported directly
  • Modify value by K: if K exists, modify the value; if K does not exist, add a key value pair.

Examples are as follows:

#1. Value by K
dic = {"name": "HammerZe", "age": 18, "hobby": "study python"}
print(dic['name'],dic['age'],dic['hobby'])
#result
HammerZe 18 study python

#K does not exist and an error is reported
print(dic['nixx'])
#result
KeyError: 'nixx'

#2. Press K to modify the value
# 1. Value by K
dic = {"name": "HammerZe", "age": 18, "hobby": "study python"}
# If k exists, it is the modified value
dic['hobby'] = 'play game'
print(dic)
# If k does not exist, add a value for
dic['sex'] = 'man'
print(dic)

#result
{'name': 'HammerZe', 'age': 18, 'hobby': 'play game'}
{'name': 'HammerZe', 'age': 18, 'hobby': 'play game', 'sex': 'man'}

2. len() -- count the number of key value pairs

  • Count the number of key value pairs in the dictionary

Examples are as follows:

# len() counts the number of key value pairs
dic = {"name": "HammerZe", "age": 18, "hobby": "study python"}
print(len(dic))

#result
3

3. Member operation

  • The member operation operates on the Key, and the Key is exposed by default

Examples are as follows:

dic = {"name": "HammerZe", "age": 18, "hobby": "study python"}
#in operation
print('age' in dic)
#not in operation
print('name' not in dic)
#The name and age keys are in the dictionary
#result
True
False

4. Delete element

  • Delete with del according to the key name
  • Pop method pop up
  • popitem method Popup

Examples are as follows:

dic = {'name': 'HammerZe', 'age': 18,
       'hobby': 'study python', 'sex': 'man'}
#  Delete according to Key, 'sex'
del dic['sex']
print(dic)

# Pop up 'age' in pop method, and print value
# dic.pop('age')
print(dic.pop('age'))
print(dic)

# popitem method
dic = {'name': 'HammerZe', 'age': 18,
       'hobby': 'study python', 'sex': 'man'}
# dic.popitem()
print(dic.popitem())  # The output pop-up content is a tuple, followed by key and value
print(dic)

5. Get() method -- get V value

  • get() write key in parentheses
  • get() gets the value. If the key does not exist, no error will be reported. Return None. Compare the key operation in the dictionary built-in method 1. If the key does not exist, an error will be reported.
  • The get() collocation parameters are: get ('key ',' value '), and the second parameter. You can customize the information when k does not exist

Examples are as follows

dic = {'name': 'HammerZe', 'age': 18,
       'hobby': 'study python', 'sex': 'man'}
#  Value by key
print(dic.get('name'))
#  Press key to get the value. If the key does not exist, return None
print(dic.get('height'))
#  When used with two parameters, if k exists, it will not change according to the following value and return the original value
print(dic.get('age', 11))  # Assignment 11 here does not change the original value
#  Use with two parameters. If k does not exist, customize the information
print(dic.get('weight', 140))  # Output information
print(dic)

6,keys( ),values( ),items( )

  • List in python2 and iterator in python3

  • Keys gets all the keys of the dictionary as a list
  • Values gets all the values of the dictionary as a list
  • items gets all key value pairs of the dictionary. The result is in the form of list tuples. The first in the tuple is key and the second is value

Examples are as follows:

dic = {'name': 'HammerZe', 'age': 18,
       'hobby': 'study python', 'sex': 'man'}
# Get all keys
print(dic.keys())
# Get all values
print(dic.values())
# Get all key value pairs
print(dic.items())

#result
dict_keys(['name', 'age', 'hobby', 'sex'])
dict_values(['HammerZe', 18, 'study python', 'man'])
dict_items([('name', 'HammerZe'), ('age', 18), ('hobby', 'study python'), ('sex', 'man')])

7. Update -- update dictionary

  • If the key exists, it will be modified; if it does not exist, it will be created

  • Compare the key operation in method 1

Examples are as follows:

# If k does not exist, add a value for
dic['sex'] = 'man'
print(dic)
#Distinguish above

#Update update dictionary
dic = {'name': 'HammerZe', 'age': 18,
       'hobby': 'study python', 'sex': 'man'}
# If key exists, modify the value
dic.update({'name':'Ze'})
print(dic)
# When the key is not present, add a key value pair
dic.update({'height':'189'})
print(dic)

#result
{'name': 'Ze', 'age': 18, 'hobby': 'study python', 'sex': 'man'}
{'name': 'Ze', 'age': 18, 'hobby': 'study python', 'sex': 'man', 'height': '189'}

8. fromkeys -- initialize dictionary

  • formkeys() method format: dict.fromkeys(seq[,value])
  • seq - dictionary key value list
  • Value - optional parameter. Set the value corresponding to the key sequence (seq). The default is None

Examples are as follows:!! written interview questions

#The second parameter is not set
dic = dict.fromkeys(['k1','k2','k3'],[])
print(dic)
dic1 = dict.fromkeys(range(5))
print(dic1)

#result
{'k1': [], 'k2': [], 'k3': []}
{0: None, 1: None, 2: None, 3: None, 4: None}

# Setting the second parameter
dic2 = dict.fromkeys(range(5),'python')
print(dic2)

#result
{0: 'python', 1: 'python', 2: 'python', 3: 'python', 4: 'python'}

3. Tuple built-in method

1. Type conversion

  • Data that can support the for loop can be converted into tuples
  • for loop iteratable objects: strings, lists, dictionaries, tuples, collections

Examples are as follows:

# print(tuple(1))  #Integer cannot be converted
# print(tuple(1.234))  # Integer cannot be converted
print(tuple('python'))  # Strings can be converted
# result
# ('p', 'y', 't', 'h', 'o', 'n')

print(tuple([1, 2, 3, 4, 5])) # Lists can be converted
# result
# (1, 2, 3, 4, 5)

print(tuple({"name":"HammerZe"})) # The dictionary can be converted to output key
# result
# ('name',)

print(tuple({1,2,3,4})) # Collections can be converted
# result
# (1, 2, 3, 4)

Note!! it is recommended to add a comma at the end of the element when the container type stores data

  • Container type definition: a data type in which multiple values can be stored

Examples are as follows:

tup = (1,)
set = {1,}
dic = {'name':'',}
print(type(tup),type(set),type(dic))
#result
<class 'tuple'> <class 'set'> <class 'dict'>

2. Index

  • Like string and list, values are obtained by subscript

Examples are as follows:

tup = (1, 2, 3, 4, 5, 6, 7)
#Forward index
print(tup[0])
#Negative index
print(tup[-1])

#result
1
7

3. Slice

Examples are as follows:

(1, 2, 3, 4, 5, 6, 7)
(1, 3, 5)
(7, 6, 5, 4, 3, 2, 1)tup = (1, 2, 3, 4, 5, 6, 7)
print(tup[0:7])
print(tup[0:-1:2])
print(tup[::-1])

#result
(1, 2, 3, 4, 5, 6, 7)
(1, 3, 5)
(7, 6, 5, 4, 3, 2, 1)

4. len() counts the number of elements

Examples are as follows:

tup = (1, 2, 3, 4, 5, 6, 7)
print(len(tup))
#result
7

5. count() counts the number of occurrences of the element

Examples are as follows:

tup = (1, 1, 2, 2, 22, 333, 44, 4, 4, 4,)
print(tup.count(4))
#result
3

6. Tuple error prone question

Tuples are read-only lists, that is, data can be queried but not modified, but we can store a list in tuple elements, so that we can change the values stored in tuples, but tuples are still immutable types, and only the list in tuples is changed.

Examples are as follows:

tup = (1, 2, 3, [4, 5, 6])
print(id(tup), type(tup))
# Append elements to the list inside the tuple
tup[3].append(7)
# result
print(tup,id(tup),type(tup))
'''see id Found no change,
Contrary to the definition of immutable types,
But what changes is the value of the list,
 The address of the list has not changed,
 The value of the address of the list in the tuple has not changed,
 So it means that the tuple has not changed'''

7. Collection built-in method

  • De duplication operation
  • Relational operation

1. Weight removal

Examples are as follows:

# Define an unordered list
s1 = {1, 4, 7, 8, 5, 2, 3, 9, 96, 2}
# The output results are also unordered
print(s1)

#result
{96, 1, 2, 3, 4, 5, 7, 8, 9}

2. Relational operation

Symbol character function
| union Union
& intersection intersection
- difference Difference set
^ symmetric_difference Symmetric difference set
> issubset subset

Examples are as follows:

There are two ways to demonstrate symbols and method names:

# Define an unordered list
s1 = {1, 2, 3, 5, 6}
s2 = {1, 2, 3, 4, 7, 8}
# Union
print(s1.union(s2))
print(s1 | s2)
# intersection
print(s1.intersection(s2))
print(s1 & s2)
# Difference set
print(s1.difference(s2))
print(s1 - s2)
# Symmetric difference set
print(s1.symmetric_difference(s2))
print(s1^s2)
#subset
print(s1.issubset(s2))
print(s1<s2)

#result
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3}
{1, 2, 3}
{5, 6}
{5, 6}
{4, 5, 6, 7, 8}
{4, 5, 6, 7, 8}
False
False

Continuous updating, seeking attention···

Keywords: Python

Added by vbracknell on Wed, 10 Nov 2021 19:48:03 +0200