当前位置:网站首页>Chapter VI - Containers
Chapter VI - Containers
2022-07-03 07:26:00 【GAVL】
Chapter six Containers
Variable : Single data
Containers : Store multiple data , Provides some methods of manipulating data
One 、 list list
characteristic :
The data types of elements are unlimited , Variable length , There is an index , Orderly , repeatable . Refer to dynamic array .
establish :
# establish
#1 use []
# It can store all kinds of data , It is generally recommended to use the same type of data .
lst=[1,2,3,'hello']
print(lst)
print(type(lst))
lst=[]# An empty list
print(lst2,bool(lst2))
#2、list() Built in functions -- Convert other types of data into lists
lst3=list(10,20,30)
print(lst3,type(lst3))
lst4=list()
print(lst4)
#3、 List generator
lst5=[i*i for i in range(1,11)]
print(lst5)
Get elements
# Get the data in the list
# List is indexed : Forward index :[0,len-1] Negative index :[-len,-1]
# Get a single element : List name [ Indexes ]
#list index out of range Index out of bounds
lst=[10,20,30,40,50,60]
#print(lst[6])
# Get multiple elements : section List name [start:end[:step]]
#start Starting index , The default value is 0
#end End index , The default value is len
# The extent of the slice :[start,end)
# The result of slicing is a copy of the original list fragment , Does not affect the original list
#step step , It can be omitted , The default value is 1
#step Positive value :start The default value is 0,end The default value is len
#step negative :start, Default end ,end The default value begins
lst2=lst[::-1]
print(lst2)
# Traverse for-in It can't be modified
print('---------for in--------')
for i in lst:
print(i)
print('---------while---------')
index=0
while index<len(lst):
print(lst[index])
index+=1
print('---------enumerate() You can traverse indexes and values ')
for index,value in enumerate(lst):
#lst[index]=12 modify
print(index,value)
# According to the element , Find the index location
# List name .index( Looking for elements ) Return the first found element location , If you can't find it , Report errors :**is not in list
lst=[1,2,3,4,5,1,1,1]
print(lst.index(1))
#in/not in Determine whether an element exists in the list
print(1 in lst)
print(10 not in lst)
add to
# add to
# Add a single element
#append() Append at the end 1 Elements
lst=[1,2,3,4,5]
print(lst,id(lst))# Check the address in memory
lst.append(0)
print(lst,id(lst))# Check the address in memory
#insert(index,ele) Specifies the index to insert , The index is too large , Add directly to the end
lst.insert(1,0)
prinr(lst)
# Add multiple elements
# List merge
lst2=[55,44,33,22,11]
lst=lst+lst2
print(lst)
#extend Expand , Merge
lst.extend(lst2)
print(lst)
# section
lst[0:2]=[11,22,33]
print(lst)
modify
# Modify individual elements
lst=[1,2,3,4,5]
lst[1]=90
print(lst)
# Modify multiple values : section
lst[4:]=[8,23,15]
print(lst)
Delete
# Delete
# Delete single element
#remove(ele) Delete by object , If you can't find it , False report
lst=[11,22,33,44,55]
lst.remove(22)
print(lst)
#pop(index) Delete by index , Don't write index, Delete the last element
lst.pop()
print(lst)
#del List name [index]
del lst[0]
print(lst)
# Empty clear()
lst.clear()
print(lst)
#del List name , After deleting , This object can no longer be used .
del lst
# reverse reverse()
Two 、 Tuples tuple
characteristic
1. Immutable sequence characteristic : Don't add, delete, or alter , After modification , The address will change
2. Reference fixed length array
3. There is an index
4. Orderly
5. Elements are not limited to types
establish
#1. Use (), Parentheses can be omitted , Only one element is , Add a comma at the end
t=(1,2,3,'hello',[1,2,3])
#2. Use built-in functions tuple()
t=tuple(11,22,33)
#3. Tuple has no generator
Get elements
# Get a single element : Indexes , non-existent , False report
t=(1,2,3,4,5)
print(t[2])
# Get multiple elements : section
print(t[1:4])
# Traverse
for i in t:
print(i)
3、 ... and 、 aggregate set
characteristic :
1. No repetition , disorder
2. Reference math set
3. Underlying implementation : Hashtable
4. Objects stored in collections are immutable
5. No index
6. The assembly is not value Dictionary
establish
#1. Use {}
s={
12,34,455,66}
#2. Use built-in functions :set()
#3. Use generative
s={
i*i for i in range(3)}
print(s)
Get elements
# No index , You can't use slices
# Traverse
s={
12,23,54,58}
for i in s:
print(i)
Additions and deletions
# increase
# Add an element add(), Add multiple elements update( Container object )
s={
12,25,36,95,45}
s.add(32)
print(s)
s.update({
13,85})
# Delete
#remove(ele) discard(ele)
# Empty clear()
Four 、 Dictionaries
characteristic :
1. All elements in the dictionary are a key value pair ,key No repetition ,value Can be repeated .
2. disorder
3.key Must be immutable
establish
# establish
#1. Use {key:value,key:value}
d={
'name':'lier','age':'18'}
# The key is immutable , Must be unique , Value types are unlimited , repeatable
# key -- value 1-1 Or many to one
#2. Use built-in functions dict()
names = ['zhangsan','lisi']
ages = [16,18]
# zip() You can package two lists , Generate tuples
print('-----------------')
z = zip(names,ages)
for item in z:
print(item)
print('-----------------')
d3 = {
name:age for name,age in zip(names,ages)}
Get elements
# Dictionaries : Get elements
# according to key Get value
d = {
'name':'Jack','age':23}
#1、d[key] ,key non-existent , Just report a mistake KeyError: 'name2'
print(d['name'])
# Dictionary name .get(key) key If it doesn't exist , Just go back to None , Default values can be given
print(d.get('name')
print(d.get('name2',' tourists '))
# Traverse
dk = d.keys()
print(dk,type(dk))
dv = d.values()
print(dv,type(dv))
di = d.items()
print(di,type(di))
print('------- Traverse key----- recommend ----')
for i in d:
print(i,d[i])
print('------- Traverse key2---------')
for i in d.keys():
print(i)
print('----------- Traversal value ')
for value in d.values():
print(value)
print('----------- Traversal key value pairs ')
for item in d.items():
print(item[0],item[1])
for key,value in d.items():
print(key,value)
# print('----------- Traversal key value pairs 3')
# for key,value in enumerate(d):
# print(key,value)
# in / not in Judge key Whether there is
print('name2' not in d) #True
Additions and deletions
# Dictionaries Additions and deletions
# increase
d ={
'name':'Tom'}
d['age']=24
print(d)
# Change
d['name']='Mary'
print('d')
d = {
'10001':['Jack',18,'1889990990']}
d['10002']=['MeiMei',16,'1660009878']
print(d)
# Delete
del d['10002']
print(d)
d.clear()
print(d)
summary
list : Orderly , repeatable , Variable length , There is an index , Any type of data []
Tuples : Orderly , repeatable , immutable , There is an index , Any type of data ()
aggregate : disorder , Do not repeat , Variable length , No index , Immutable data {}
Dictionaries : disorder ,key No repetition ,value repeatable , Variable length , No index , There are keys , Key value pair (key Immutable data ){ }
Chapter vii. character string
# character string
s = 'python,python'
#index From left to right , The first occurrence of this character / The position of the string , If it doesn't exist , False report ValueError: substring not
found
print(s.index('py'))
#rindex() From right to left , The first occurrence of this character / The position of the string , If it doesn't exist , False report ValueError: substring
not found
print(s.rindex('py'))
#find From left to right , The first occurrence of this character / The position of the string , If it doesn't exist , return -1
print(s.find('py3'))
#rfind From right to left , The first occurrence of this character / The position of the string , If it doesn't exist , return -1
print(s.rfind('py3'))
# Judge
print('-------------')
s2 = 'sss'
#isalpha() Determine whether the string is all letters
print(s2.isalpha())
#isdecimal() Are all decimal numbers
print(s2.isdecimal())
#isnumeric() Include Chinese numbers , Roman numerals, etc
print(s2.isnumeric())
#isalnum() Whether it's all letters or numbers
print(s2.isalnum())
print(' chinese '.isidentifier())#True
# Case conversion
s3 = 'Python'
print(s3.upper())
print(s3.lower())
# Compare
# == Compare content
s4 ='Python'
print(s3==s4)
# is Compare addresses , That is to say, comparison id
print(s3 is s4) #True
print(id(s3),id(s4))
''' Several cases of resident mechanism 1 String length is 0/1 2、 Rules for matching identifiers 3、[-5,256] '''
# String splitting split( Separator )-- Returns the split list
s='hello,python'
s2=s.split(',')
print(s2,type(s2))
# String merging Separator string .join( Iteratable object ) --- Returns the merged string
s3 = '/'.join(s2)
print(s3,type(s3))
# String replacement
s4='hello,python'
s5=s4.replace('python','Java')
print(s5)
s6='http://www.baidu.com'
# startswith() Whether or not to xxx start
print(s6.startswith('http:'))
print(s6.endswith('com'))
边栏推荐
猜你喜欢
《指環王:力量之戒》新劇照 力量之戒鑄造者亮相
Various postures of CS without online line
JS monitors empty objects and empty references
Deep learning parameter initialization (I) Xavier initialization with code
Custom generic structure
PAT甲级真题1166
Leetcode 198: 打家劫舍
Pat grade a real problem 1166
Understanding of class
Leetcode 213: 打家劫舍 II
随机推荐
Advanced APL (realize group chat room)
Talk about floating
Beginners use Minio
3311. Longest arithmetic
691. 立方体IV
Custom generic structure
【无标题】
Advanced API (batch image Download & socket dialog)
C代码生产YUV420 planar格式文件
II. D3.js draw a simple figure -- circle
Strategy mode
Introduction of transformation flow
Wireshark software usage
Basic components and intermediate components
Use of framework
[set theory] order relation (partial order relation | partial order set | example of partial order set)
不出网上线CS的各种姿势
Operation and maintenance technical support personnel have hardware maintenance experience in Hong Kong
Use of other streams
Hello world of vertx