Basic operation of the list of python must learn series

Application of list index subscript to find whether an element in the list exists

name = ["daq","qwdwq","eqw","ewqq","eqwoj"]
#元素获取的使用:下标 索引
print(name[0])
print(name[3])

#获取最后一个元素
print(name[-1])
print(name[len(name)-1])

#获取第一个元素
print(name[0])

daq
ewqq
eqwoj
eqwoj
daq


例题:判断某个元素在不在列表中

方法一:使用for循环的模式
name = ["daq","qwdwq","eqw","ewqq","eqwoj"]
#列表的循环
# for i in name:
#     print(i)
#查询列表中是否有eqw
for i in name:
    if i == "eqw":
        print("eqw已经找到")
        break
else:
    print("没有找到")

eqw已经找到

方法2:使用in参数
name = ["daq","qwdwq","eqw","ewqq","eqwoj"]
if 'eqw' in name:
    print("找到元素")
else:
    print("没有找到")

找到元素


List of CRUD operations

1) Change operation----->To combine the use of subscripts

The essence of the modification operation of the list is to find the subscript of the element that needs to be modified.

name = ["daq","qwdwq","中国","ewqq","神州"]
##如果已经知道要修改的元素在;列表中的某个位置,此时修改起来就比较的简单
# 1:找到下标 2:通过'='进行重新赋值 3:新的值覆盖原来的值
name[-1] = "shenzhou"
print(name)

['daq', 'qwdwq', '中国', 'ewqq', 'shenzhou']


##如果只知道眼修改的元素但是不知道元素对应的下标,此时就要结合for循环没来遍历找到元素对应的下标
##列表中元素的修改,一个基本的概念就是一定要找到元素对应的下标,然后在进行重新的赋值

方法1:
name = ["daq","qwdwq","中国","ewqq","神州"]
for i in range(len(name)):
    if name[i] == "中国":     ###这种使用==进行判断的,判断的标准是:name[i]对应的字符串就是'中国'
        name[i] = "China"
        break
print(name)

方法2:使用in
name = ["daq","qwdwq","中国","ewqq","神州"]
for i in range(len(name)):
    if "中国" in name[i]: ##而这种方法,判断的标准是:之言name[i]对应的字符串中之只要含有中国就可以
        print(i)
        name[i] = "China"
        break
print(name)

2
['daq', 'qwdwq', 'China', 'ewqq', '神州']

2) Delete operation of the list (del)

Important: The central idea of ​​the delete operation of the list is to find the subscript of the corresponding element

note:

If you need to delete multiple elements in the list at a time, you need to use a while loop instead of a for loop

Because the for loop is used, for i in range(len(list)), when a delete operation is performed, the length of the list is reduced by one.

Will there be an error in the loop traversal in the future:

##如果只删除列表中的一个元素,此时使用for循环也可以

name = ["hp","mac","中国","dell","神州"]
for i in range(len(name)):
    if name[i] == "mac":
        del name[i]
        break    ###此处一定要使用break,删除之后就直接退出循环,这样子才不会报错
print(name)

##如果需要在列表中删除的元素不是一个,而是多个,此时就不可以使用for循环,会报错

name = ["hp","mac","中国","dell","神州"]
for i in range(len(name)):
    if name[i] == "mac" or name == "dell":
        del name[i]
print(name)

IndexError: list index out of range   ##因为当执行完依次删除操作之后,列表的长度就减1了,当下次在循环遍历的时候就会出现list index out of range的情况。因为起始的len(name)长度是不会变化的。


当执行多个删除任务的时候可以考虑while循环。

name = ["hp","mac","中国","dell","神州"]
i = 0   ##  i 指的是下标
l = len(name)
while i < l:
    if "mac" in name[i] or "dell" in name[i]:
        print(i)
        del name[i]
        l -=1  ##每次执行完一次删除的操作之后就将列表的总长度减1。
    i+=1
print(name)

1
2
['hp', '中国', '神州']

Examples of list deletion operations:

一个列表为:words = ['a','b','c','d','e','yz']
输入一个你想删除的单词,删除之后将新的列表返回出来

方法一:使用for循环
words = ['a','b','c','d','e','yz']
word = input("请输入你想删除的单词:")
for i in range(len(words)):
    if words[i] == word:
        del words[i]
        break
print(words)


请输入你想删除的单词:a
['b', 'c', 'd', 'e', 'yz']

方法2:使用while循环

words = ['a','b','c','d','e','yz']
word = input("请输入你想删除的单词:")
i = 0
l = len(words)
while i < l:
        if words[i] == word:
            del words[i]
            l -=1
        i+=1
print(words)

请输入你想删除的单词:yz
['a', 'b', 'c', 'd', 'e']

Delete the omissions in the list; (use continue to solve)

Experimental scenario: I want to delete elements that contain go characters in the list

words = ['hello','goods','good','world','digot','alphago']
word = input("请输入你想删除的单词:")
i = 0
l = len(words)
while i < l:
        if word in words[i]:
            del words[i]
            l -=1
        i+=1
print(words)

请输入你想删除的单词:go
['hello', 'good', 'world', 'alphago']   ### 此时发现就会存在一个漏删的现象,因为每次执行一次删除操作,列表的长度减1,索引下标加1。

分析:刚开始的 i=0,l=6 第一个元素为hello,没有执行删除的操作。
     此时;l=6 i=1 此时遍历到goods,因为含有go字段,将其删除,执行了一次删除的操作。
        列表变为 ['hello','good','world','digot','alphago']
     此时:l=5 i=2 问题就出在我进行一次删除的操作,然后还将i+1了,此时在我新的列表中,索引下标为2    
           是world,就将我的good给跳过去了,此时就会造成一个漏删的现象


解决方法:使用continue,当我额米茨执行完依次删除的操作之后,我的i都不进行加1,此时就可以将漏删的问题给解决了


words = ['hello','goods','good','world','digot','alphago']
word = input("请输入你想删除的单词:")
i = 0
l = len(words)
while i < l:
        if word in words[i]:
            del words[i]
            l -=1
            continue
        i+=1

print(words)

请输入你想删除的单词:go
['hello', 'world']
    
    

remove method and pop()

remove(e) ##删除列表中第一次出现的指定元素,返回值是个none,如果没有找到需要删除的元素,则会报错
name = ["sd","yz","flo","gli","gok","kui"]
name.append("yz")
name1=name.remove("yz")
print(name1)
print(name)

None
['sd', 'flo', 'gli', 'gok', 'kui', 'yz']

pop()   ###删除列表中的最后一个元素,返回值是被删除的那个元素

pop() 默认是可以不进行传输参数的,不过也指定我想删除的元素,但是和remove方法不同的是,remove智慧而指定你想删除的元素,但是pop参数加的是你想删除的元素对应的下标

name = ["sd","yz","flo","gli","gok","kui"]
print(name.pop())
print(name)


kui   ###可以看到pop操作的返回值是被删除的那个元素
['sd', 'yz', 'flo', 'gli', 'gok']


name = ["sd","yz","flo","gli","gok","kui"]
print(name.pop(3))   ###删除列表中,下标为3对应的元素
print(name)

gli
['sd', 'yz', 'flo', 'gok', 'kui']

Clear method

name = ["sd","yz","flo","gli","gok","kui"]
name.clear()
print(name)

[]

 

The slice index rule of the list [ start: end: specify direction and step length ]

Same as the slice index of the string

 

Add operation to list

The function of the add operation of the list: append extend insert

 

append appends to the end of the list

append() 末尾追加
#append是在列表的末尾追加一个元素,默认追加到列表的末尾
name = ["ad"]
while True:
    add_name = input("请输入你想添加的人(输入quit则表示退出)")
    if add_name == 'quit':
        break
    else:
         name.append(add_name)
print(name)

请输入你想添加的人(输入quit则表示退出)qe
请输入你想添加的人(输入quit则表示退出)eq
请输入你想添加的人(输入quit则表示退出)fqq
请输入你想添加的人(输入quit则表示退出)quit
['ad', 'qe', 'eq', 'fqq']

 

extend is used to merge lists,'+' can be used not only to concatenate strings but also to merge lists

#extend 列表的合并,用于在一个列表的后面追加一个列表。
name1 = ['qw','qdq']
name2=  ['dq','fgs','sgs','hfg']
name1.extend(name2)
print(name1)

['qw', 'qdq', 'dq', 'fgs', 'sgs', 'hfg']

‘+‘ 也可以用于列表的合并
name1 = ['qw','qdq']
name2=  ['dq','fgs','sgs','hfg']
print(name1+name2)

['qw', 'qdq', 'dq', 'fgs', 'sgs', 'hfg']

 

insert insert, you can specify to insert an element at a certain position in the list

name=  ['dq','fgs','sgs','hfg']
name.insert(1,'jl')  ##将jl这个元素添加到列表的下标为1的位置,其余的元素向后推迟
print(name)

['dq', 'jl', 'fgs', 'sgs', 'hfg']

 

Example: Randomly generate 10 random numbers and save them in the list

import random
num = []
for i in range(10):
    ran = random.randint(1,20)
    num.append(ran)
print(num)

[3, 7, 8, 11, 5, 16, 17, 7, 4, 18]

###此时发现,随机生成的10个元素里面会有重复的元素
如果 要求生成的10个元素里面不能有重复的元素,那么应该怎么办呢?此时就要使用while循环

import random
num = []
i =0
while i <10:
    ran = random.randint(1,20)
    if ran not in num:
        num.append(ran)
        i+=1         ###注意这个i+=1 一定要在if判断的里面,这样子在执行成功以后才执行加1操作
print(num)


[1, 11, 4, 16, 12, 15, 13, 19, 2, 8]

 

Example: Find the maximum value in the list

1: Use the built-in method max() of the list

import random
num = []
i = 0
while i < 10:
    ran = random.randint(1, 20)
    if ran not in num:
        num.append(ran)
        i += 1
print(num)
##使用列表的max函数求出列表中的最大值
max_num = max(num)
print(max_num)

[5, 13, 20, 18, 12, 2, 11, 4, 7, 10]
20

2: Use for loop plus comparison to find the maximum and minimum

import random
num = []
i = 0
while i < 10:
    ran = random.randint(1, 20)
    if ran not in num:
        num.append(ran)
        i += 1
print(num)
max_num = num[0]  ##假设最大的值为列表的第一个值
min_num = num[0]
for i in  num:
    if i > max_num:  ##遍历循环整个列表,然后将取得值逐次与我自己定义的max_num值进行比较。
        max_num = i  ##每次将比较滞后最大的值复制给max_num,就可以找到最大列表中最大的值
    if i < min_num:
        min_num = i  ##取最小值
print(max_num)
print(min_num)

[15, 6, 2, 19, 8, 5, 18, 16, 17, 7]
19
2

 

Example: Summation of numbers in a list

1: Use the sum function to sum

import random
num = []
i = 0
while i < 10:
    ran = random.randint(1, 20)
    if ran not in num:
        num.append(ran)
        i += 1
print(num)
##使用sum求和函数进行求和
sum1 = sum(num)
print(sum1)

[18, 12, 19, 3, 6, 5, 1, 9, 4, 15]
92

2: Use for loop to sum

import random
num = []
i = 0
while i < 10:
    ran = random.randint(1, 20)
    if ran not in num:
        num.append(ran)
        i += 1
print(num)
sum1 =0
for i in num:
    sum1+=i
print(sum1)

[9, 7, 1, 18, 13, 12, 8, 20, 2, 11]
101

 

Example: How to sort the list

1: Use sorted sorting method

sorted(list) ---> The default is ascending

sorted(list, reserve=True) --->At this time, it becomes sorted in descending order

import random
num = []
i = 0
while i < 10:
    ran = random.randint(1, 20)
    if ran not in num:
        num.append(ran)
        i += 1
print(num)
sort_num=sorted(num)
print(sort_num)


[3, 11, 13, 16, 6, 4, 19, 7, 2, 15]
[2, 3, 4, 6, 7, 11, 13, 15, 16, 19]

import random
num = []
i = 0
while i < 10:
    ran = random.randint(1, 20)
    if ran not in num:
        num.append(ran)
        i += 1
print(num)
sort_num=sorted(num,reverse=True)   ###指定为降序进行排序
print(sort_num)

[17, 4, 7, 9, 2, 11, 15, 14, 19, 3]
[19, 17, 15, 14, 11, 9, 7, 4, 3, 2]

 

Use of two-dimensional lists (lists are nested in the list)

list1=[[1,2,3],[5,7,8],['a','v',8]]
print(list1[2][1])  ###取出v
print(list1[0][2])  ###取出3

v
3

 

Type conversion: what can be converted into a list

Type conversion:

str()

int() --->The numbers in the list cannot be directly converted to integers ---> The numbers in the string can be converted to integers

list() ##Convert the specified content into a list. But the content must be iterable.

What can be iterated? ----> It means that the elements in the content can be taken out one by one.

The contents of for ... in ... can be iterated, that is, what can be used in a for loop is iterable

String range() can be iterated

Numbers cannot be iterated

###字符串转列表
a = 'adj'
list1=list(a)
print(list1)

['a', 'd', 'j']

###range操作的返回结果都是可以转换成列表的
print(list(range(1,10)))
print(list(range(5)))
print(list(range(1,10,3)))

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4]
[1, 4, 7]

###一个数字就不可以转换成list的
list1=list(8)
print(list1)

TypeError: 'int' object is not iterable   ###错误显示,int的数据类型不能转换成列表的

 

The method of reversing the list is reverse (equivalent to outputting the list in reverse order)

name = ["sd","yz","flo","gli","gok","kui"]
name.reverse()
print(name)


['kui', 'gok', 'gli', 'flo', 'yz', 'sd']

 

How to sort the list

System provided method sorted(list) list.sort()

name = [2,42,63,33,73,72,84]
sorted(name)
print(name)

name1 = [2,42,63,33,73,72,84]
name1.sort()
print(name1)


[2, 42, 63, 33, 73, 72, 84]
[2, 33, 42, 63, 72, 73, 84]

 

 

The use of enumerate() function: convert an iterable object into subscript and value form (list string can be used)

Operation on the list:

list1 = ['dqq','oqj','hsj','hau']
for index,value in enumerate(list1):
    print(index,value)

0 dqq     ###输出了列表的元素和其对应的下标
1 oqj
2 hsj
3 hau


也可以单独获取下标或者元素
list1 = ['dqq','oqj','hsj','hau']
for index,value in enumerate(list1):
    print(value)
    print(index)

dqq
0
oqj
1
hsj
2
hau
3

Operations on strings

for index,value in enumerate("hello"):
    print(index,value)


0 h
1 e
2 l
3 l
4 o

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/yinzhen_boke_0321/article/details/104525249