Python theoretical knowledge (5) basic variable types

1. List

1.1, basic concepts

  • The list is an ordered collection of elements, all elements are placed in a pair of square brackets, separated by commas, and there is no length limit;
  • The list index value starts at 0, and - 1 is the starting position from the end.
  • Lists can be concatenated using the + operator, and * for repetition.
  • When list elements are added or deleted, the list object automatically expands or shrinks memory to ensure that there is no gap between elements;
  • elements in the list can be of different types

1.2. How to use the list

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
list = ["tsinbei","blog","blog.tsinbei.com",1234,[0,1,2,[1,2]]]

#create a list

# A list can have multiple data types

#You can even nest lists to make 2D or 3D lists

print(list[0])
print(list[2])
print(list[4][2])
print(list[4][3][0])
print(list[-1])
print(list[-2])

result:

Comment first then view it after your comment is approved. Join QQ Group to display all hidden texts.

1.3, the basic operation of the list

list operatoroperator meaning
< list1 > + < list2 >join two lists
* repeats the list an integer number of times
[]index element in list
len( < seq > )get the number of elements in the list
for < var > in < list > :loop through the list
[ : ]take a subsequence of the list
in member check to see if is in a list

methodmethod meaning
< list >.append( x )add element x to the end of the list
< list >.sort( )sort list elements, default is ascending
< list >.reverse( )Reverse list elements
< list >.index( )Returns the index of the first occurrence of element x
< list >.insert( i, x )insert new element x at position i
< list >.count( x )returns the number of elements x in the list
< list >.remove( x )remove the first occurrence of the element x in the list
< list >.pop( i )pops the element at position i in the list and deletes it
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
>>> a = [2,0,9,1,5]
>>> b = ['c','w','b','a']
>>> a.append(9)
>>> a
[2, 0, 9, 1, 5, 9]
>>> a.sort()
>>> a
[0, 1, 2, 5, 9, 9]
>>> a.reverse()
>>> a
[9, 9, 5, 2, 1, 0]
>>> b.sort()
>>> b
['a', 'b', 'c', 'w']
>>> a.index(5)
2
>>> a.insert(2,7)
>>> a
[9, 9, 7, 5, 2, 1, 0]
>>> a.count(9)
2
>>> a.remove(9)
>>> a
[9, 7, 5, 2, 1, 0]
>>> a.pop(0)
9
>>> a
[7, 5, 2, 1, 0]

1.5, list comprehension

  • List comprehensions (aka list comprehensions) provide a concise and concise way to create lists.
  • It is structured to enclose an expression in square brackets, followed by a for statement, followed by zero or more for or if statements. That expression can be arbitrary, meaning you can put any type of object in the list. The return result will be a new list, produced after the expression in the context of the if and for statements has completed.
  • Execution order of list comprehension: There is a nested relationship between the statements, the second statement on the left is the outermost layer, and the first statement on the left is the last layer.
Python
1
2
3
4
5
data = [i for i in range(10)]
#Equivalent to
data = []
for i in range(10):
    data.append(i)
Python
1
2
3
4
5
data = [2**i for i in range(10)]
#Equivalent to
data = []
for i in range(10):
    data.append(2**i)
Python
1
2
3
4
5
6
data = [num for num in range(20) if num%2==1]
#Equivalent to
data = []
for num in range(20):
    if num%2==1:
        data.append(num)

1.6, application

topic:

There are 3 offices in 1 school. Now there are 8 teachers waiting for the assignment of workstations. Please write a program to complete the random assignment.

Answer:

Comment first then view it after your comment is approved. Join QQ Group to display all hidden texts.

The running result is as follows:

2, tuple

2.1, basic concepts

  • A tuple is a type containing multiple elements, separated by commas
    Such as: t1 = (123,456,"hello")
  • A tuple can be created by enclosing several elements in a pair of parentheses, adding an extra comma if only one element, such as (3,).
  • You can also use the tuple() function to convert lists, dictionaries, sets, strings, and range objects, map objects, zip objects, or other similar objects into tuples.
  • Tuple can be empty, t2=()
  • A tuple can also be used as an element of another tuple. In this case, parentheses need to be added to the tuple as an element to avoid ambiguity, such as: t3=(123,456,("hello","world"))
  • Python tuples are similar to lists, except that the elements of the tuple cannot be modified.

2.2, the use of tuples

Python
1
2
3
4
5
>>> a = ('hello',2020,110)
>>> a
('hello', 2020, 110)
>>> a[1]
2020

The element value in the tuple is not allowed to modify and delete, but we can use the del statement to delete the entire tuple.

Python
1
2
3
4
5
6
7
8
9
>>> a = ('hello',2020,'blog.tsinbei.com')
>>> print(a)
('hello', 2020, 'blog.tsinbei.com')
>>> del a
>>> print(a)
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    print(a)
NameError: name 'a' is not defined

The so-called immutability of a tuple means that the contents of the memory pointed to by the tuple are immutable.

Python
1
2
3
4
5
6
7
8
9
10
>>> tup = ('r', 'u', 'n', 'o', 'o', 'b')
>>> tup[0] = 'g' # Modifying elements is not supported
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> id(tup) # View memory address
4440687904
>>> tup = (1,2,3)
>>> id(tup)
4441088800 # The memory address is different

3. Dictionary

3.1, basic concepts

  • A dictionary is an unordered collection of objects, using key-value (key-value) storage, with extremely fast lookup speed.
  • keys must use immutable types
  • In the same dictionary, the key (key) must be unique
  • Each key-value key => value pair of the dictionary is separated by a colon:, and each key-value pair is separated by a comma, and the entire dictionary is enclosed in curly braces }, the format is as follows:
  • dic = {key1 : value1, key2 : value2 }
  • Dictionary keys are generally unique. If the last key-value pair is repeated, the previous one will be replaced, and the value does not need to be unique.
  • keys must be immutable, so can be used as numbers, strings or tuples

example:

Python
1
2
3
>>> tsinbei = {'website':'blog.tsinbei.com','name':'HsukqiLee'}
>>> tsinbei['website']
'blog.tsinbei.com'

3.2, common methods

MethodDescription
keys()Returns a list of keys in a dictionary
values()returns a list of values ​​in a dictionary
items()Returns a list of tuples. Each tuple consists of a dictionary key and corresponding value
clear()removes all entries of the dictionary
copy()Returns a copy of the high-level structure of the dictionary, but does not copy the embedded structures, only references to those structures
update(x)Update dictionary contents with key-value pairs in dictionary x.
get(x[,y]))returns the key x, if the key is not found, it returns none, if y is provided, it returns y if it is not retrieved
str(x)output dictionary x as a string
len(x)Returns the number of elements in dictionary x, that is, the total number of keys.
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> tsinbei = {'website':'blog.tsinbei.com','name':'HsukqiLee'}
>>> tsinbei.keys()
dict_keys(['website', 'name'])
>>> tsinbei.values()
dict_values(['blog.tsinbei.com', 'HsukqiLee'])
>>> tsinbei.items()
dict_items([('website', 'blog.tsinbei.com'), ('name', 'HsukqiLee')])
>>> tsinbei.copy()
{'website': 'blog.tsinbei.com', 'name': 'HsukqiLee'}
>>> test = {'website':'pan.tsinbei.com'}
>>> tsinbei.update(awsl)
>>> tsinbei
{'website': 'pan.tsinbei.com', 'name': 'HsukqiLee'}
>>> tsinbei.get('website') 'pan.tsinbei.com'
>>> tsinbei.get('tsinbei','666')
'666'
>>> tsinbei.clear()
>>> tsinbei
{}
>>> dict = {'Name':'HsukqiLee', 'Age': 20, 'Class': 'First'}
>>> str(dict)
"{'Name': 'HsukqiLee', 'Class': 'First', 'Age': 20}"

3.3, dictionary element modification, addition and deletion

  • You can use the pop() of the dictionary object to delete the element corresponding to the specified "key" and return the corresponding "value"
  • The popitem() method removes a key pair from the dictionary and returns a tuple containing two elements, the "key" and "value" of the dictionary element.
  • You can also use del to delete the element corresponding to the specified "key".

4. Collection

4.1. Overview

  • Python collections are unordered, mutable container objects. All elements are placed in a pair of curly brackets, and the elements are separated by commas. Each element in the same collection is The only , no repetition is allowed,
  • Collections can only contain data of immutable types such as numbers, strings, tuples, etc., while ** cannot contain data of variable types such as lists, dictionaries, sets, etc., including lists and other variable types of data Tuples of are also not allowed as elements of a collection.
  • The elements in the collection are unordered, and the order of storage and addition of elements is not consistent.
  • Collections do not support using subscripts to directly access elements at specific positions, nor do they support using the choice() function in random to randomly select elements from the collection, but support using sample() in the random module The function randomly selects some elements.

4.2, set (collection)

  • Set is similar to dict, it is also a set of keys, but does not store value. Since keys cannot be repeated, there are no repeated keys in the set.
  • The set is unordered, duplicate elements are automatically filtered in the set.
  • Sets can be created using curly braces { } or set() functions. Note: to create an empty set, set() must be used instead of { }, because { } is used to create an empty set dictionary.
  • A set can be regarded as a collection of unordered and non-repetitive elements in a mathematical sense. Therefore, two sets can perform operations such as intersection (&), well set (|), and difference set (-) in the mathematical sense.

4.3. Common methods of collection

  • s = add(x): add element x to set s, do nothing if the element already exists.
  • s = update(x): Add the elements of x to the set s, where x can be a list, tuple, dictionary, etc.
  • s.pop(x): Randomly remove an element from the set.
  • s.remove(x): remove element x from set s, an error occurs if the element does not exist.
  • s.discard(x): remove the element x from the set s, if the element does not exist, no error will occur.
  • len(s): Count the number of elements in the set s.
  • s.clear(): clears the collection s.

5. String

5.1. Overview

  • A string (str) is one or more characters enclosed in double quotes "" or single quotes ''
  • Strings can be stored in variables or by themselves
  • Strings are immutable objects, all methods return the processed string or byte string without any modification to the original string.

5.2, String operations

  • Strings can be connected by + or *

    • The addition operation (+) concatenates two strings into a new string
    • The multiplication operation (*) generates a string that is repeatedly concatenated of its own strings
    • x in s: if x is a substring of s, return True, otherwise return False
    • str[N:M]: slice, return substring
  • The len() function can return - the length of a string

    • str1="hello,world"
    • len(str1)
  • Most data types can be converted to strings by the str() function: e.g. str(123)
  • The type() function tests the type of a string

5.3, String operations

ActionMeaning
+connect
*repeat
< string >[ ]index
< string >[ : ]cut
len()length
< string >.upper()uppercase letters in string
< string >.lower()lowercase letters in string
< string >.strip()Strip spaces and specified characters on both sides
.split()Split string by specified character into array
.join()joins two sequences of strings
.find()Search for the specified string
.replace()string replacement
for < var > in < string >string iteration
  • index(x), rindex(x): Check if x is contained in the string, return the corresponding index value, if not. Returns an exception.
  • count(x): Returns the number of occurrences of x in string.
  • replace(str1,str2[,max]): replace str1 in the string with str2, if max is specified, the replacement will not exceed max times.
  • maketrans(): Create a translation table for character mappings.
  • translate(str): Translate string characters according to the mapping conversion table given by str.
  • ljust(width[,fllchar]): Returns a left-justified string of the original string, padded to a new string of length width using fillchar, which defaults to spaces. rjust(), center() are similar.
  • split(str="",num=string.count(str)), where num=string.count(str)) uses str as the delimiter to intercept the string, if num has a specified value , then only num+1 substrings are intercepted. rsplit() is similar, truncating from the right.
  • join(seq): Combines all elements (string representations) in seq into a new string with the specified string as the delimiter.
  • startswith(substr), endswith(substr): Check whether the string starts or ends with the specified substring substr, and returns True if it is.
  • strip(), rstrip(), lstrip(): Strip the specified characters of the string.

6, string formatting

SymbolDescription
%cformat character and its ASCII code
%sformat string
%dformatted integer
%uformat unsigned int
%oformat unsigned octal number
%xformat unsigned hexadecimal number
%Xformat unsigned hexadecimal number (uppercase)
%fFormat a floating point number, specifying the precision after the decimal point
%eformat floating point number in scientific notation
%ESame as %e, format floating point numbers in scientific notation
%gfloating point data will remove excess zeros and keep at most 6 bits
%Gfloating-point data will remove excess zeros and keep at most 6 bits
%pformat the address of the variable in hexadecimal

6.2. Formatting operator auxiliary instructions:

Operation SymbolDescription
*define width or decimal point precision
-for left alignment
+Displays a plus sign ( + ) before positive numbers
< sp >Display spaces before positive numbers
\#Displays zero ('0') in front of octal numbers, '0x' or '0X' in front of hexadecimal numbers (depending on whether 'x' or 'X' is used)
0The displayed number is padded with '0' instead of the default space
%'%%' outputs a single '%'
(var)map variable (dictionary parameter)
m.n.m is the minimum total width displayed, n is the number of digits after the decimal point (if available)

6.3. Application

Write a program that fulfills the following requirements:

Count the number of each character in the string
eg: "hello world"
The result of string statistics is
h:1 e:1 l:3 o:2 d:1 r:1 w:1

Answer:

Python
1
2
3
4
5
6
7
8
9
a="hello world"
b=[]
for i in a.replace(" ",""):
    if i in b:
        pass
    else:
        b.append(i)
for i in b:
    print("%s:%s"%(i,a.count(i)))

7. Thanks

Reprinted from:
Zeruns's Blog

Python theoretical knowledge (5) basic variable types

https://blog.tsinbei.com/en/archives/593/

Author
Hsukqi Lee
Posted on

2022-07-11

Edited on

2022-07-28

Licensed under

CC BY-NC-ND 4.0

Comments

Name
Mail
Site
None yet