当前位置:网站首页>04. basic data type - list, tuple
04. basic data type - list, tuple
2022-06-26 05:52:00 【qq_ forty-two million four hundred and seventy-two thousand nin】
Catalog
One 、 list
1.1 List introduction
列 Table is python The basic data type of ⼀, Other programming languages ⾔ There are similar data types . such as JS In the array , java Arrays in etc . It is a [ ] Cover up , Every element ⽤’ , ' Separate and store all kinds of data types :
list = [1, ' ha-ha ', " Woo hoo ", [1,8,0," Baidu "], (" I "," It's called ", " element ", " Group "), "abc", {
" My name is ":"dict Dictionaries "},{
" I'm the assembly "," aggregate "}]
Lists are compared to characters 串. Not only can different types of data be stored , And it can be stored and enlarged 量 The data of .32 position python It can store : 536870912 Elements , 64 It can store : 1152921504606846975 Elements . And the list is ordered ( In the order you save ), There is an index , Can cut ⽚⽅便 Value .
2.2 列 Indexing and slicing of tables
列 Tables, like strings, have indexes :
list = [" Gentiana ", " still 林", "⻢ Yun ", " Doctor Zhou Hong ", " Xiang Huaqiang "]
print(list[0]) # For the first ⼀ Elements
print(list[1]) # For the first ⼀ Elements
print(list[2]) # For the first ⼀ Elements
list[3] = " Strong mobility " # Be careful . Column 列 Tables can be sent ⽣ Make a difference . this ⾥ in 里 And string 串 Dissimilarity
print(list) # [' Gentiana ', ' Wang Jianlin ', '⻢ Yun ', ' Strong mobility ', ' Xiang Huaqiang ']
s0 = " Xiang Huaqiang "
s0[1] = " beautiful " # TypeError: 'str' object does not support item assignment The value in the string cannot be changed
print(s0)
Slice of the list :
list = [" Gentiana ", " still 林", "⻢ Yun ", " Doctor Zhou Hong ", " Xiang Huaqiang "]
print(list[0:3]) # [' Gentiana ', ' still 林', '⻢ Yun ']
print(list[:3]) # [' Gentiana ', ' still 林', '⻢ Yun ']
print(list[1::2]) # [' still 林', ' Doctor Zhou Hong '] There are steps ⻓
print(list[2::-1]) # ['⻢ Yun ', ' still 林', ' Gentiana '] You can also take it backwards
print(list[-1:-3:-2]) # Step backwards ⻓
Two 、 Add, delete, modify and search the list
- increase Be careful : list and str It is not ⼀ What kind of ,list Can send ⽣ Change , So go straight to the original object ⾏了 operation .
Increase method | detailed |
---|---|
append() | Add elements at the end of the list |
insert() | Insert the element at the index position of the specific list , The following elements are automatically moved back |
extend() | The specified list element ( Or any iteratable element ) Add to the end of the current list |
list = [" Gentiana ", "林 Junjie ", " Chow yun-fat ", " Zhou Zhiruo "]
print(list) # [' Gentiana ', '林 Junjie ', ' Chow yun-fat ', ' Zhou Zhiruo ']
list.append("wusir")
print(list) # [' Gentiana ', '林 Junjie ', ' Chow yun-fat ', ' Zhou Zhiruo ', 'wusir']
list = []
while True:
content = input(" Please enter your record ⼊ I'm a member of the team ⼯ Information , Input Q sign out :")
if content.upper() == 'Q':
break
list.append(content)
print(list)
list = [" Gentiana ", " Zhangdezhong ", " Kondefu "]
list.insert(1, " Lau Andy ") # stay 1 The position of the plug ⼊ Lau Andy . The original element moves back ⼀ a
print(list) # [' Gentiana ', ' Lau Andy ', ' Zhangdezhong ', ' Kondefu ']
# Add... Iteratively
list = [" Wang Zhiwen ", " Zhang ⼀ mountain ", " Boundless sea of pain "]
list.extend([" Gentiana ", " Hemp flowers 不 Pain, "])
print(list) # [' Wang Zhiwen ', ' Zhang ⼀ mountain ', ' Boundless sea of pain ', ' Gentiana ', ' Hemp flowers 不 Pain, ']
2. Delete
Delete method | detailed |
---|---|
pop() | Delete the element at the index position corresponding to the list , Delete the last... By default |
remove() | Delete the first specified element in the list |
clear() | clear list |
del | Delete list elements as index subscripts |
list = [" Gentiana ", " still 林", " Li Jiacheng ", " Wang Fugui "]
print(list)
deleted = list.pop() # Delete the last one
print(" The deleted ", deleted) # The deleted wangfugui
print(list) # [" Gentiana ", " still 林", " Li Jiacheng "]
el = list.pop(2) # Delete 2 Element number
print(el) # Li Jiacheng
print(list) # [" Gentiana ", " still 林"]
list.remove(" Gentiana ") # Deletes the specified element
print(list) # [" still 林"]
# list.remove(" ha-ha ") # Deleting nonexistent elements will result in an error
# print(list)
# Empty list
list.clear()
print(list) # []
# Slice delete
list = [" Gentiana ", " still 林", " Li Jiacheng ", " Wang Fugui "]
del list[0:3]
print(list) # [' Wang Fugui '] Go to the head but not the tail
- modify
Modification method | detailed |
---|---|
Index modification | Select the list elements by index and re assign values |
Slice modification | Select multiple elements of the list by slicing to re assign values |
# modify
list = [" The white ", " It's too dark ", " Five colors ", " King of silver ", " Day day "]
list[1] = " Too dirty " # hold 1 The number element has been modified to be too dirty
print(list) # [" The white ", " Too dirty ", " Five colors ", " King of silver ", " Day day "]
list[1:4:3] = [" Gentiana ", " tencent "] # cut ⽚ Modification is also OK. If the step length is not 1, it is to be noted that . Number of elements
print(list) # ValueError: attempt to assign sequence of size 2 to extended slice of size 1
list[1:4:2] = [" Gentiana ", " tencent "]
print(list) # [' The white ', ' Gentiana ', ' Five colors ', ' tencent ', ' Day day ']
list[1:4] = [" Li Jiacheng "] # If cut ⽚ No step ⻓ Or step ⻓ yes 1. No ⽤ Turn off ⼼ Number
print(list) # [' The white ', ' Li Jiacheng ', ' Day day ']
- Inquire about
Query methods | detailed |
---|---|
for loop | 列 Table is ⼀ Iteratable objects , So you can go in 行 for Mix and match if Judge , Filter query |
in | Returns if a value is found in the specified sequence True, Otherwise return to False |
list = [" too ⽩", " It's too dark ", " Five colors ", " King of silver ", "⽇ God "]
for i in list:
if i == ' King of silver ':
print(i)
break
else:
print(" I didn't find ")
print(" King of silver " in list)
- Other operating
Other operating | detailed |
---|---|
count() | Count the number of elements in a list |
sort() | Sort the elements in the list in ascending order |
reverse() | Negate the elements in the list |
len() | Find the number of all elements in the list |
list = [" The white ", " It's too dark ", " Five colors ", " King of silver ", "⽇ God ", " too ⽩"]
c = list.count(" too ⽩") # The query is too ⽩ Number of occurrences
print(c)
list = [1, 11, 22, 2]
list.sort() # Sort . Default ascending order
print(list)
list.sort(reverse=True) # Descending
print(list)
list = [" too ⽩", " too ⿊", " 5、 ... and ⾊", " King of silver ", "⽇ God ", " too ⽩"]
print(list)
list.reverse()
print(list)
l = len(list) # List ⻓ degree
print(l)
3、 ... and 、 Nesting of lists
Use dimension reduction operation , Just look at it layer by layer
list = [1, " too ⽩", "wusir", ["⻢⻁ Pain, ", [" Coca Cola "], " Wang Jianlin "]]
# find wusir
print(list[2])
# Find too ⽩ and wusir
print(list[1:3])
# Find too ⽩ Of ⽩ word
print(list[1][1])
# take wusir Get . then ⾸ word ⺟⼤ Write . Throw it back
s = list[2]
s = s.capitalize()
list[2] = s
print(list)
# Abbreviation
list[2] = list[2].capitalize()
print(list)
# Put too ⽩ Change to too ⿊
list[1] = list[1].replace("⽩", "⿊")
print(list)
# hold ⻢⻁ Change the pain into ⻢ Relieve pain
list[3][0] = list[3][0].replace("⻁", " turn ")
print(list[3][0])
# Add sprite to the list of Coca Cola
list[3][1].append(" Sprite ")
print(list)
Four 、 Tuples and tuples nesting
Tuples : Commonly known as immutable list .⼜ Be made a read-only list , Tuples are also python The basic data type of ⼀, ⽤⼩ Enclosed in brackets , 里⾯ You can put any kind of data , Queries can be 、 The cycle can also 、 Slices can also be 、 But it can't be changed ( increase 、 Delete ).
tu = (1, " too ⽩", " Li ⽩", " too ⿊", " Yes? ⿊")
print(tu)
print(tu[0])
print(tu[2])
print(tu[2:5]) # After slicing, it's still tuple
# for Cycle through the epoch group
for el in tu:
print(el)
# Try to modify tuples
# tu[1] = " Careless pain " # Report errors 'tuple' object does not support item assignment
tu = (1, " ha-ha ", [], " ha-ha ")
# tu[2] = ["fdsaf"] # This change is not ⾏
tu[2].append(" Gentiana ") # It can be changed . No mistake
tu[2].append(" Wang Jianlin ")
print(tu) #(1, ' ha-ha ', [' Gentiana ', ' Wang Jianlin '], ' ha-ha ')
About immutability , Be careful : this 里 The immutability of tuples means that the child elements are immutable , And inside the child element ⼦ Elements can be changed , It depends. ⼦ Whether the element is a mutable object
If there is only ⼀ Elements . ⼀ Be sure to add ⼀ Commas , Otherwise it's not a tuple
tu = (1,)
print(type(tu))
Tuples also have count(), index(), len() Other methods . You can test it yourself
5、 ... and 、 range
range It can help us get a set of data . adopt for The loop can get these data
for num in range(10):
print(num)
for num in range(1, 10, 2):
print(num)
for num in range(10, 1, -2): # On the contrary , He Che ⽚ slice ⼀ equally
print(num)
Review questions
- What does a list do ?
- How to get the elements in the list ?
- What are the ways to add elements to the list ? What's the difference between them ?
- How to delete the elements of the list ? What's the difference between them ?
- How to modify the elements in the list ? What's the difference between them ?
- What are the methods to query the elements in the list ? What's the difference between them ?
- How to count the number of elements in a list ?
- How to sort the elements in the list in ascending order ?
- How to negate elements in a list ?
- How to find the number of all elements in the list ?
- Encountered multi nested list , How to operate on list elements ?
- Tuples vs. lists , What are the characteristics of each ?
- range What does the function do ? What is the method of use ?
边栏推荐
- 【 langage c】 stockage des données d'analyse approfondie en mémoire
- Redis usage and memory optimization
- 类和对象的学习
- Ribbon load balancing service call
- one billion two hundred and twelve million three hundred and twelve thousand three hundred and twenty-one
- Soft power and hard power in program development
- kolla-ansible部署openstack yoga版本
- Class and object learning
- Kolla ansible deploy openstack Yoga version
- Test depends on abstraction and does not depend on concrete
猜你喜欢
C generic speed
从新东方直播来探究下小程序音视频通话及互动直播
Operator priority, associativity, and whether to control the evaluation order [detailed explanation]
pytorch(环境、tensorboard、transforms、torchvision、dataloader)
电商借助小程序技术发力寻找增长突破口
The purpose of writing programs is to solve problems
Kolla ansible deploy openstack Yoga version
MySQL database-01 database overview
LeetCode_ Binary search tree_ Simple_ 108. convert an ordered array to a binary search tree
Gram 矩阵
随机推荐
Consul service registration and discovery
Win socket programming (Mengxin initial battle)
SQL Server 函数
A new explanation of tcp/ip five layer protocol model
写在父亲节前
售前分析
Test depends on abstraction and does not depend on concrete
循环位移
Force buckle 875 Coco, who likes bananas
RIA想法
MySQL database-01 database overview
About XXX management system (version C)
A new journey
About abstact and virtual
Kolla ansible deploy openstack Yoga version
MEF framework learning record
MySQL数据库-01数据库概述
Daily production training report (17)
【群内问题学期汇总】初学者的部分参考问题
Soft power and hard power in program development