Python basic grammar knowledge (2)

miscellaneous

  • If a tab /tcannot be aligned, several more can be added;

  • Only when the dictionary is converted into a string, the value of the dictionary will be retained, and the value will be lost when converted into a set, list, or tuple

function

Example 1:

str1 = "hello world"
# 函数定义
def my_len(data):
    count = 0
    for i in data:
        count += 1
    print(f"字符串{
      
      data}长度为{
      
      count}")

my_len(str1) #!!!

Output:
The length of the string hello world is 11

Example 2: If no return value is specified, None is returned

def multi(x, y):
    result = x * y
    print(f"{
      
      x} + {
      
      y} 的计算结果:{
      
      result}" )

res1 = multi(3, 2)

output:

The result of calculating 3 + 2: 6

None

None is equivalent to False

Example 3: Adding comments to functions

Use multiline comments

def multi(x, y):
    """
    :param x:
    :param y:
    :return: x * y的结果
    """
    result = x * y
    print(f"{
      
      x} + {
      
      y} 的计算结果:{
      
      result}")
    return result

Example 4: Global and local variables

num = 200

def test_b():
    global  num # 加上global 表明和外面全局的num是同一个数字
    num = 500
    print(f"test_b:{
      
      num}")

test_b() # test_b:500
print(num) # 500

the list

The list index can be negative , -1 represents the last element

Example 1: Index is negative

name_list = ['nokia', True, 22]
print(name_list[-1])
print(name_list[-2])
print(name_list[-3])
print(type(name_list))

output:

22

True

nokia

<class ‘list’>

A function placed in a class is called a method

Example 2: The extend function appends elements in batches

mylist1 = ["apple", "banana", "python"]
mylist2 = [2, 3, 4]
mylist1.extend(mylist2)
print(mylist1) # ['apple', 'banana', 'python', 2, 3, 4]

Common List Methods

image-20230608212450899

tuple

main point

  • Multiple, different types of elements can be stored but cannot be modified , defined with ();
  • If a list is nested in the tuple, the list can be modified;
  • Tuples can be nested ;

Example 1

t1 = (1, "hello", False)
t2 = ()
t3 = tuple()
t4 = ("good") # 只有一个元素会被识别为str类型,要加一个,才会是元组类型
t5 = ("bad", )
print(f"t1类型为{
      
      type(t1)}, 内容为{
      
      t1}")
print(f"t1类型为{
      
      type(t2)}, 内容为{
      
      t2}")
print(f"t1类型为{
      
      type(t3)}, 内容为{
      
      t3}")
print(f"t1类型为{
      
      type(t4)}, 内容为{
      
      t4}")
print(f"t1类型为{
      
      type(t5)}, 内容为{
      
      t5}")

output

The type of t1 is <class 'tuple'>, the content is (1, 'hello', False)

The type of t1 is <class 'tuple'>, and the content is ()

The type of t1 is <class 'tuple'>, and the content is ()

t1 type is <class 'str'>, content is good

The type of t1 is <class 'tuple'>, the content is ('bad',)

Example 2: Methods of tuples

t1 = ("good", "bad", "well", "best", "worse", "good")
index = t1.index("best") # 查找"best"在t1中的索引
print(f"best 在t1中的索引为{
      
      index}")

num = t1.count("good") # 查找good在t1中出现次数
print(f"good 在t1中出现次数{
      
      num}")

len_t1 = len(t1)
print(f"t1中元素个数:{
      
      len_t1}")
# 元素遍历
index = 0
while index < len_t1:
    print(f"t1[{
      
      index}] = {
      
      t1[index]}")
    index += 1

output:

The index of best in t1 is 3

good occurs 2 times in t1

Number of elements in t1: 6

t1[0] = good

t1[1] = bad

t1[2] = well

t1[3] = best

t1[4] = worse

t1[5] = good

Example 3: The nested list in the tuple can be modified

t2 = (1, 2, ["hello", "world"])
print(f"t2内容为{
      
      t2}")
t2[2][0] = "apple"
t2[2][1] = "pear"
print(f"t2内容为{
      
      t2}")

output

The content of t2 is (1, 2, ['hello', 'world'])

The content of t2 is (1, 2, ['apple', 'pear'])

string

Example 1: String replacement replace

Note that replacement does not modify the value of the original string, but returns a new replaced string

my_str = "Royal never giveup"

new_mystr = my_str.replace("never", "forever")
print(f"将字符串{
      
      my_str}替换后得到{
      
      new_mystr}") #将字符串Royal never giveup替换后得到Royal forever giveup

Example 2: Splitting the string split will also not modify the original string

my_str = "Royal never giveup"
# 将my_str 按照空格切分,得到列表
my_str_list = my_str.split(" ")
print(f"将字符串{
      
      my_str}进行切分后得到:{
      
      my_str_list}, 类型是: {
      
      type(my_str_list)}")
# 将字符串Royal never giveup进行切分后得到:['Royal', 'never', 'giveup'], 类型是: <class 'list'>

Example 3: Remove the specified character strip before and after

my_str = "  Royal never giveup  "
# 不传入参数,则去除前后空格
new_my_str = my_str.strip()
print(f"字符串:{
      
      my_str}调用strip后,结果为:{
      
      new_my_str}")

my_str = "23Royal never giveup32"
# 去除my_str 前后的"2" 和 "3"
new_my_str = my_str.strip("23")
print(f"字符串:{
      
      my_str}调用strip后,结果为:{
      
      new_my_str}")

output

String: Royal never giveup After calling strip, the result is: Royal never giveup

String: 23Royal never giveup32 After calling strip, the result is: Royal never giveup

slice

Example 1

# 切片操作
my_list = [1, 2, 3, 4, 5, 6]
result = my_list[1:4]
print(result) # [2, 3, 4]

# 对tuple切片
my_tuple = (2, 3, 4, 5, 6)
result2 = my_tuple[:]
print(result2) # (2, 3, 4, 5, 6)

gather

Collections are defined setusing {}and do not allow storing duplicate elements

Example 1

my_set = {
    
    "你好", "我好", "大家好", "我好", "大家好", "我好"}
my_set_empty = set() # 定义空集合
print(f"my_set的内容是:{
      
      my_set}, 类型是{
      
      type(my_set)}")
print(f"my_set_empty:{
      
      my_set_empty}, 类型是{
      
      type(my_set_empty)}")

my_set.add("python")
my_set.add("你好")
print(f"my_set添加元素后的结果是:{
      
      my_set}")

my_set.remove("大家好")
print(f"my_set移除元素后的结果是:{
      
      my_set}")

my_set = {
    
    "你好", "我好", "大家好"}
element = my_set.pop() # 随机取出一个元素,注意是随机取
print(f"集合被取出的元素是:{
      
      element}, 取出元素后:{
      
      my_set}")

output

The content of my_set is: {'Hi everyone', 'Hello', 'Hello'}, the type is <class 'set'>

my_set_empty: set(), type is <class 'set'>

The result of adding elements to my_set is: {'Hi everyone', 'Hello', 'python', 'Hello'}

The result of removing elements from my_set is: {'I'm good', 'python', 'Hello'}

The elements taken out of the collection are: Hello everyone, after taking out the elements: {'Hello', 'Hello'}

Example 2: Take difference set difference

set1 = {
    
    1, 2, 3}
set2 = {
    
    1, 5, 6}
# 取set1里有而set2里没有的元素
set3 = set1.difference(set2)
print(f"取出差集后的结果是:{
      
      set3}")
print(f"取出差集后,原有set1内容:{
      
      set1}")
print(f"取出差集后,原有set2内容:{
      
      set2}")

output:

The result after taking the difference is: {2, 3}

After taking out the difference set, the original set1 content: {1, 2, 3}

After taking out the difference set, the original set2 content: {1, 5, 6}

Example 3: Eliminate identical elements

set1 = {
    
    1, 2, 3}
set2 = {
    
    1, 5, 6}
# 消除 set1 中 与 set2中相交的元素
set1.difference_update(set2)
print(f"消除差集后,set1:{
      
      set1}")
print(f"消除差集后,set2:{
      
      set2}")

output

After eliminating the difference set, set1: {2, 3}

After eliminating the difference set, set2: {1, 5, 6}

Example 4: Merge collection union

Union will deduplicate

set1 = {
    
    1, 2, 3}
set2 = {
    
    1, 5, 6}

# 两集合合并
set3 = set1.union(set2)
print(f"合并集后,set3:{
      
      set3}")
print(f"合并集后,set1:{
      
      set1}")
print(f"合并集后,set2:{
      
      set2}")

output

After merging sets, set3: {1, 2, 3, 5, 6}

After merging sets, set1: {1, 2, 3}

After merging sets, set2: {1, 5, 6}

dictionary

Example 1: Basic usage

my_dict1 = {
    
    "周杰伦" : 87, "林俊杰" : 99, "陈奕迅" : 88}
# 定义空字典
my_dict2 = {
    
    }
my_dict3 = dict()
print(f"字典1的内容是:{
      
      my_dict1}, 类型是:{
      
      type(my_dict1)}")
print(f"字典2的内容是:{
      
      my_dict2}, 类型是:{
      
      type(my_dict2)}")
print(f"字典3的内容是:{
      
      my_dict3}, 类型是:{
      
      type(my_dict3)}")

# 定义重复key的字典,字典的key不允许重复
my_dict1 = {
    
    "周杰伦" : 87, "周杰伦" : 99, "陈奕迅" : 88}
print(f"重复key的字典内容是:{
      
      my_dict1}")

output:

The content of dictionary 1 is: {'Jay Chou': 87, 'JJ Lin': 99, 'Eason Chan': 88}, the type is: <class 'dict'>

The content of dictionary 2 is: {}, the type is: <class 'dict'>

The content of dictionary 3 is: {}, the type is: <class 'dict'>

The content of the dictionary with repeated keys is: {'Jay Chou': 99, 'Eason Chan': 88}

Example 2: Defining nested dictionaries

stu_score_dict = {
    
    
    "周杰伦":{
    
    
        "语文":88,
        "数学":99,
        "英语":92
    },
    "林俊杰":{
    
    
        "语文":99,
        "数学":87,
        "英语":93
    },
    "陈奕迅":{
    
    
        "语文":84,
        "数学":99,
        "英语":99
    }
}

score = stu_score_dict["周杰伦"]["英语"]
print(f"周杰伦的英语成绩为:{
      
      score}")

score = stu_score_dict["陈奕迅"]["数学"]
print(f"陈奕迅的数学成绩为:{
      
      score}")

output:

Jay Chou's English score is: 92

Eason Chan's math score: 99

Example 3: Common operations on dictionaries

my_dict1 = {
    
    "周杰伦" : 87, "林俊杰" : 99, "陈奕迅" : 88}
score = my_dict1.pop("周杰伦") # 删除 key 为周杰伦的 pair
print(f"字典中被移除了一个元素,结果为:{
      
      my_dict1}, 周杰伦的考试分数是:{
      
      score}")

# 获取字典中全部的key
my_dict1 = {
    
    "周杰伦" : 87, "林俊杰" : 99, "陈奕迅" : 88}
keys = my_dict1.keys()
print(f"字典的全部keys是{
      
      keys}")

# 对字典遍历
print("--------------")
for key in keys:
    print(f"字典的key是:{
      
      key}")
    print(f"字典的value是:{
      
      my_dict1[key]}")

output:

An element has been removed from the dictionary, and the result is: {'JJ Lin': 99, 'Eason Chan': 88}, Jay Chou's test score is: 87

All the keys of the dictionary are dict_keys(['Jay Chou', 'JJ Lin', 'Eason Chan'])

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

The key of the dictionary is: Jay Chou

The value of the dictionary is: 87

The key of the dictionary is: JJ Lin

The value of the dictionary is: 99

The key of the dictionary is: Eason Chan

The value of the dictionary is: 88

Example 4: Sorting of various containers

my_list = [1, 2, 9, 4, 5]
my_tuple = (1, 8, 2, 7, 2)
my_str = "abcdefs"
my_set = {
    
    1, 4, 2, 8, 22}
my_dict = {
    
    "key1": 1, "key2": 2, "key3": 3, "key4": 4, "key5": 5}

print(f"列表对象排序的结果:{
      
      sorted(my_list)}")
print(f"元组对象排序的结果:{
      
      sorted(my_tuple)}")
print(f"字符串对象排序的结果:{
      
      sorted(my_str)}")
print(f"集合对象排序的结果:{
      
      sorted(my_set)}")
print(f"字典对象排序的结果:{
      
      sorted(my_dict)}")

print("----------------")
print(f"列表对象反向排序的结果:{
      
      sorted(my_list,reverse=True)}")
print(f"元组对象反向排序的结果:{
      
      sorted(my_tuple,reverse=True)}")
print(f"字符串对象反向排序的结果:{
      
      sorted(my_str,reverse=True)}")
print(f"集合对象反向排序的结果:{
      
      sorted(my_set,reverse=True)}")
print(f"字典对象反向排序的结果:{
      
      sorted(my_dict,reverse=True)}")

output:

The result of sorting list objects: [1, 2, 4, 5, 9]

The result of sorting tuple objects: [1, 2, 2, 7, 8]

String object sorted result: ['a', 'b', 'c', 'd', 'e', ​​'f', 's']

The result of sorting collection objects: [1, 2, 4, 8, 22]

The result of sorting dictionary objects: ['key1', 'key2', 'key3', 'key4', 'key5']

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

The result of reverse sorting of list objects: [9, 5, 4, 2, 1]

The result of reverse sorting of tuple objects: [8, 7, 2, 2, 1]

The result of reverse sorting of string objects: ['s', 'f', 'e', ​​'d', 'c', 'b', 'a']

The result of reverse sorting of collection objects: [22, 8, 4, 2, 1]

The result of reverse sorting of dictionary objects: ['key5', 'key4', 'key3', 'key2', 'key1']

Guess you like

Origin blog.csdn.net/qq_42120843/article/details/131116616