Python learning Chapter 10 advanced variable types

Advanced variable type

The data types are digital and non digital


Non numeric variables:

Data type details

List list

The most frequently used data type is often called an array in other languages
Function: use a variable to store multiple data.

name_list = ['zs', 'ls', 'ww']
print(name_list)

['zs', 'ls', 'ww']


Take the first data

name_list = ['zs', 'ls', 'ww']
print(name_list)
print(name_list[0])

['zs', 'ls', 'ww']
zs

The list is a large grid with multiple small grids. Take out the data and read it according to the small grid number, starting from 0

List operation

There are 11 actions for the list:
example:

Value:
For example

name_list[0]

Fetch index
Location of output data

name_list = ['zs', 'ls', 'ww']
print(name_list)

print(name_list.index('zs'))

['zs', 'ls', 'ww']
0

modify

name_list = ['zs', 'ls', 'ww']
print(name_list)
name_list[0] = 'I'
print(name_list)

['zs', 'ls', 'ww']
['I', 'ls',' ww ']

increase
append
Add data to last face

name_list = ['zs', 'ls', 'ww']
print(name_list)
name_list.append('Wang Xiaoer')
print(name_list)

['zs', 'ls', 'ww']
['zs',' ls', 'ww', 'Wang Xiaoer']
insert
Insert data at the specified index location

name_list = ['zs', 'ls', 'ww']
print(name_list)
name_list.insert(0, 'Wang Xiaoer')
print(name_list)

['zs', 'ls', 'ww']
['Wang Xiaoer', 'zs',' ls', 'ww']

extend
Batch add subsequent arrays to the end of the first array

name_list = ['zs', 'ls', 'ww']
print(name_list)
a = ["Add 1", 'Add 2', 'Add 3']
name_list.extend(a)
print(name_list)

['zs', 'ls', 'ww']
['zs',' ls', 'ww', 'add 1', 'add 2', 'add 3']

Delete data
remove
clear
pop bomb

remove
Delete specified data

name_list = ['zs', 'ls', 'ww']
print(name_list)
a = ["Add 1", 'Add 2', 'Add 3']
name_list.extend(a)
print(name_list)
name_list.remove('Add 1')
print(name_list)

['zs', 'ls', 'ww']
['zs',' ls', 'ww', 'add 1', 'add 2', 'add 3']
['zs',' ls', 'ww', 'add 2', 'add 3']

pop
The last element in the list is deleted by default

name_list = ['zs', 'ls', 'ww']
print(name_list)
a = ["Add 1", 'Add 2', 'Add 3']
name_list.extend(a)
print(name_list)
name_list.pop()
print(name_list)

['zs', 'ls', 'ww']
['zs',' ls', 'ww', 'add 1', 'add 2', 'add 3']
['zs',' ls', 'ww', 'add 1', 'add 2']

pop specifies to delete the element index

name_list = ['zs', 'ls', 'ww']
print(name_list)
a = ["Add 1", 'Add 2', 'Add 3']
name_list.extend(a)
print(name_list)
name_list.pop(0)
print(name_list)

['zs', 'ls', 'ww']
['zs',' ls', 'ww', 'add 1', 'add 2', 'add 3']
['ls',' ww ',' add 1 ',' add 2 ',' add 3 ']

clear
Empty tuple list

name_list = ['zs', 'ls', 'ww']
print(name_list)
a = ["Add 1", 'Add 2', 'Add 3']
name_list.extend(a)
print(name_list)
name_list.clear()
print(name_list)

['zs', 'ls', 'ww']
['zs',' ls', 'ww', 'add 1', 'add 2', 'add 3']
[]

del
del essentially deletes the variable from memory
del xxx[n]

name_list = ['zs', 'ls', 'ww']
print(name_list)
a = ["Add 1", 'Add 2', 'Add 3']
name_list.extend(a)
print(name_list)
del name_list[0]
print(name_list)

['zs', 'ls', 'ww']
['zs',' ls', 'ww', 'add 1', 'add 2', 'add 3']
['ls',' ww ',' add 1 ',' add 2 ',' add 3 ']

Summary:

Statistics

name_list = ['zs', 'ls', 'ww']
print(name_list)
a = ["zs", 'Add 2', 'Add 3']

print(len(name_list))
print(name_list.count('zs'))

['zs', 'ls', 'ww']
3
1

List counts the number of elements in the list
. count counts the number of occurrences of an element

sort

List (. Sort)
Ascending - default

name_list = ['zs', 'ls', 'ww']
num_list = [2, 5, 6, 1, 7, 3, 6, 5]

print(name_list)
print(num_list)
name_list.sort()
num_list.sort()
print(name_list)
print(num_list)

['zs', 'ls', 'ww']
[2, 5, 6, 1, 7, 3, 6, 5]
['ls', 'ww', 'zs']
[1, 2, 3, 5, 5, 6, 6, 7]

Descending order

name_list = ['zs', 'ls', 'ww']
num_list = [2, 5, 6, 1, 7, 3, 6, 5]

print(name_list)
print(num_list)
name_list.sort(reverse=1)
num_list.sort(reverse=1)
print(name_list)
print(num_list)

['zs', 'ls', 'ww']
[2, 5, 6, 1, 7, 3, 6, 5]
['zs', 'ww', 'ls']
[7, 6, 6, 5, 5, 3, 2, 1]

Keyword function method difference

Use keywords without parentheses
Using functions and methods requires parentheses

Keywords are characters that represent special meanings. When used, parentheses are not required
When using functions and methods, parentheses must be used. Sometimes parameters need to be used inside parentheses
Methods are for objects

Loop traversal

Traversal: get data from the list from beginning to end
Iterative traversal: repeat traversal, repeatedly taking out one element after another from the list.

Iterative traversal using for

name_list = ['zs', 'ls', 'ww']

for i in name_list:
    print(i)

zs
ls
ww

Obtain data from the list in sequence. In each cycle, the data will be saved in i, and the data obtained this time can be accessed inside the cycle body.

for i in list variable:
print i

List application scenarios

Lists store the same type of data
Through iterative traversal, the same operation is performed for each element within the loop body.

Note, however, that lists in python can store different types of data.
For example:

name_list = ['zs', 'ls', 'ww', 1, 1.75]

for i in name_list:
    print(i)

But this kind of situation is rarely encountered!!!

tuple

Composed of multiple elements
Element cannot be modified
The index also starts from 0
Tuples are defined with (), and lists are defined with []
Once tuples are defined, they cannot be modified (added, deleted or modified)
Different types of data can be saved

Take the element

tuple = ('zs', 18, 18.5)

print(tuple[0])

zs

When defining tuples, you should pay attention to defining tuples that contain only one element!!! a = (xx,) followed by element,

Fetch index

You already know the content of the data and want to know the index of the data in the tuple

tuple = ('zs', 18, 18.5)

print(tuple.index("zs"))

0

Statistical counting

tuple.count('zs')
len(tuple)

The principle is the same as list

Traversal tuple

tuple = ('zs', 18, 18.5)

for i in tuple:
    print(i)

In tuples, the data types saved are usually different

Application scenario of tuple

Define the parameters of the function
Return value of function
Format string
Make the list non modifiable to protect data security.

a = ("Meow", 21, 1.85)
print("%s Age is %d Height is%.2f" % a)

Conversion between list and tuple

Dictionaries

The most flexible data type
Used to store unordered data types
{}
The dictionary has key and value
Key value pairs save data
Key: get information
Values: saving information

Information usually used to describe an item

example:

Value

xiaoming = {"name": "Meow"}

print(xiaoming['name'])

Meow

Add & modify

xiaoming = {"name": "Meow"}

xiaoming['age'] = 12
print(xiaoming)
xiaoming = {"name": "Meow"}

xiaoming['age'] = 12

print(xiaoming)
xiaoming['name'] = 'quinoa '
print(xiaoming)

delete

pop specified key deletion

xiaoming = {"name": "Meow"}

xiaoming['age'] = 12
print(xiaoming)
xiaoming.pop('age')
print(xiaoming)

Count the number of key value pairs

xiaoming = {"name": "Meow"}

xiaoming['age'] = 12

print(len(xiaoming))

Merge dictionary

update

xiaoming = {"name": "Meow"}
x = {"age": 12, "gender": 1}
xiaoming.update(x)
print(xiaoming)

Note that if the merged key value pairs are the same key, the following key will overwrite the previous key

Empty dictionary

clear()

xiaoming = {"name": "Meow"}
print(xiaoming)

Loop traversal dictionary

xiaoming = {"name": "Meow", "age": 21, "gender": "female"}

for i in xiaoming:
    print(i)

name
age
gender

xiaoming = {"name": "Meow", "age": 21, "gender": "female"}

for i in xiaoming:
    print(xiaoming[i])

Meow
21
female

Application scenario

A dictionary stores multiple attributes of an object
Put multiple dictionaries in a list, store them, and traverse them when you use them

card_list = [
    {"name": "joe",
     "qq": 123,
     "phone": 12312},
    {"name": "kitty",
     "qq": 234,
     "phone": 34324}
]

for i in card_list:
    print(i)

{'name': 'joe', 'qq': 123, 'phone': 12312}
{'name': 'kitty', 'qq': 234, 'phone': 34324}

character string

A pair of double quotation marks or single quotation marks can define a string

str1 = "hello python"
str2 = "My nickname is big watermelon"

Gets the element in the string

str1 = "hello python"
str2 = "My nickname is big watermelon"

print(str2)
print(str1[6])

My nickname is big watermelon
p

The for loop fetches characters from a string

str2 = "My nickname is big watermelon"

for i in str2:
    print(i)

Count the number of strings

print(len(str1))
print(str1.count('h'))

Take out the position of the character

str1 = "hello python"
print(str1.index('h'))

0

String related methods

Summary of is judgment type method:


Case conversion:

Determine whether the string is empty

str1 = "hello python"
str2 = "  \t\n\r" # \r means back to the beginning of the line
print(str1.isspace())
print(str2.isspace())

Digital judgment

print(str2.isdecimal())
print(str2.isdigit())
print(str2.isnumeric())

From top to bottom, the judgment criteria are more and more broad

Replace and find

str1 = "hello python"
str2 = "1.5\t\n\r"  # \r means back to the beginning of the line

print(str1.startswith("hello"))
print(str1.endswith("on"))
print(str2.find("5"))  # Returns the index position of the data
# The find method returns - 1 if the string does not exist. The index method returns an error if the string does not exist
# print(str2.index("123"))
print(str2.find("123"))

# Replace hello with hi
print(str1.replace("hello", "hi"))

align text
Case:
Climb the stork tower

poem = ["Climb the stork tower",
        "wang zhihuan",
        "At the end of the day,",
        "The Yellow River flows into the sea.",
        "If you want to be poor,",
        "Take it to the next level."]

for i in poem:
    print('|%s|' % i.center(10, " "))
    # print('|%s|' % i.rjust(10, " "))

|Climb the stork tower|
|Wang Zhihuan|
|At the end of the day|
|The Yellow River flows into the sea|
|If you want to be poor|
|Take it to the next level|

De duplicate white space character

Articles crawled from the Internet will be irregular and need to remove spaces

poem = ["\t\n Climb the stork tower",
        "wang zhihuan",
        "At the end of the day,\t\n",
        "The Yellow River flows into the sea.",
        "If you want to be poor,",
        "Take it to the next level."]

for i in poem:
    # Use the strp method to remove whitespace from a string
    i = i.strip()
    print('|%s|' % i.center(10, " "))

Split and connect

poem_str = "\t\n Climb the stork tower\t wang zhihuan\t The day is at the end of the mountain\t\n The Yellow River flows into the sea\t in order to see far away\t\r\t Take it to the next level."

list = poem_str.split()
print(list)
a = "\n".join(list)
print(a)

Slicing of strings

Slicing uses index values to limit the range, cutting out small strings from large strings
Lists and tuples are i game sets, and the corresponding data can be obtained through index
Dictionaries are unordered and use key value pairs to store data

Specifies the start index and end index step

For example:
Intercept 2-5 numbers
Intercept 2 to the last number
Intercept start to data 5
Intercepts the complete string
Intercept every 1 character

Intercept the penultimate character

Intercept the last two characters

Intercept the reciprocal string

Tags: Python Pycharm

Posted on Tue, 21 Sep 2021 20:14:58 -0400 by kaisellgren