list (list) And a tuple (tuple) More similar , They all keep the elements in order , All elements occupy a contiguous block of memory , Each element has its own index , Therefore, the elements of lists and tuples can be indexed (index) To visit . The difference is : The list can be modified , Tuples are immutable .
Dictionaries (dict) And collection (set) The stored data is out of order , Each element occupies different memory , Where dictionary elements are represented by key-value Form preservation of
Just to be clear ,Python There are no arrays in , But added a more powerful list
Lists can store integers 、 decimal 、 character string 、 list 、 Any type of data, such as tuples , And the types of elements in the same list can be different
num = [1, 2, 3, 4, 5, 6, 7]
name = ["C Chinese language network ", "http://c.biancheng.net"]
program = ["C Language ", "Python", "Java"]
# Convert string to list
list1 = list("hello")
print(list1)
# Converts a tuple to a list
tuple1 = ('Python', 'Java', 'C++', 'JavaScript')
list2 = list(tuple1)
print(list2)
# Convert dictionary to list
dict1 = {
'a':100, 'b':42, 'c':9}
list3 = list(dict1)
print(list3)
# Convert interval to list
#range() Function can easily generate a series of numbers , Give Way Python Start with the first value specified , Count until the specified second value stops , But not the second value
range1 = range(1, 6)
list4 = list(range1)
print(list4)
# Create an empty list
print(list())
Index from 0 Start , use len() Function to get list Number of elements , When the index is out of range ,Python Will report a IndexError error , therefore , Make sure that the index doesn't cross the boundary , Remember that the index of the last element is len(classmates) - 1.
listname[start : end : step]
among ,listname Indicates the name of the list ,start Indicates the starting index ,end Indicates end index ,step Indicating step size .
url = list("http://c.biancheng.net/shell/")
# Use the index to access an element in the list
print(url[3]) # Use positive index
print(url[-4]) # Use negative index
# Use slices to access a set of elements in the list
print(url[9: 18]) # Use positive slices
print(url[9: 18: 3]) # Specify the step size
print(url[-6: -1]) # Use negative slices
language = ["Python", "C++", "Java"]
birthday = [1991, 1998, 1995]
info = language + birthday
print("language =", language)
print("birthday =", birthday)
print("info =", info)
listname.append(obj)
among ,listname Represents the list of elements to be added ;obj Represents the data added to the end of the list , It can be a single element , It could be a list 、 Tuples etc. .
l = ['Python', 'C++', 'Java']
# Additional elements
l.append('PHP')
print(l)
# Append tuple , The whole tuple is treated as an element
t = ('JavaScript', 'C#', 'Go')
l.append(t)
print(l)
# Add list , The whole list is also treated as an element
l.append(['Ruby', 'SQL'])
print(l)
extend() and append() The difference is that :extend() You don't think of lists or Yuanzu as a whole , Instead, they add the elements they contain to the list one by one .
extend() The syntax of the method is as follows :
listname.extend(obj)
among ,listname Refers to the list of elements to be added ;obj Represents the data added to the end of the list , It can be a single element , It could be a list 、 Tuples etc. , But it can't be a single number .
l = ['Python', 'C++', 'Java']
# Additional elements
l.extend('C')
print(l)
# Append tuple , Yuanzu was split into multiple elements
t = ('JavaScript', 'C#', 'Go')
l.extend(t)
print(l)
# Add list , The list is also split into multiple elements
l.extend(['Ruby', 'SQL'])
print(l)
append() and extend() Method can only insert elements at the end of the list , If you want to insert an element somewhere in the middle of the list , Then you can use insert() Method .
listname.insert(index , obj)
among ,index The value represents the position of the specified index .insert() Will obj Insert into listname The list of the first index The location of the elements .
l = ['Python', 'C++', 'Java']
# Insert elements
l.insert(1, 'C')
print(l)
# Insert tuples , The whole Yuanzu is regarded as an element
t = ('C#', 'Go')
l.insert(2, t)
print(l)
# Insert list , The whole list is treated as an element
l.insert(3, ['Ruby', 'SQL'])
print(l)
# Insert string , The whole string is treated as an element
l.insert(0, "http://c.biancheng.net")
print(l)
stay Python The deleted elements in the list are mainly divided into the following 3 Kinds of scenes :
del You can delete individual elements from the list , The format is :
del listname[index]
among ,listname Represents the name of the list ,index Represents the index value of the element .
lang = ["Python", "C++", "Java", "PHP", "Ruby", "MATLAB"]
# Use positive index
del lang[2]
print(lang)
# Use negative index
del lang[-2]
print(lang)
del You can also delete a continuous element in the middle , The format is :
del listname[start : end]
lang = ["Python", "C++", "Java", "PHP", "Ruby", "MATLAB"]
del lang[1: 4]
print(lang)
lang.extend(["SQL", "C#", "Go"])
del lang[-5: -2]
print(lang)
among ,start Indicates the starting index ,end Indicates end index .del Will delete from index start To end Between the elements , barring end The element of location .
Python pop() Method is used to delete the element at the specified index in the list , The specific format is as follows :
listname.pop(index)
among ,listname Represents the name of the list ,index Indicates the index value . If you don't write index Parameters , The last element in the list is deleted by default
nums = [40, 36, 89, 2, 36, 100, 7]
nums.pop(3)
print(nums)
nums.pop()
print(nums)
remove() Method will only delete the first element with the same value as the specified value , And the element must be guaranteed to exist , Otherwise, it will cause ValueError error .
nums = [40, 36, 89, 2, 36, 100, 7]
# First deletion 36
nums.remove(36)
print(nums)
# Delete for the second time 36
nums.remove(36)
print(nums)
# Delete 78
nums.remove(78)
print(nums)
Python clear() Used to delete all elements of the list , That is, empty the list , Look at the code below :
url = list("http://c.biancheng.net/python/")
url.clear()
print(url)
Python Two modification lists are provided (list) Element method , You can modify individual elements at a time , You can also change a set of elements at a time ( Multiple ).
Modifying individual elements is very simple , You can assign values directly to the elements . Please see the following example :
nums = [40, 36, 89, 2, 36, 100, 7]
nums[2] = -26 # Use positive index
nums[-3] = -66.2 # Use negative index
print(nums)
Python Supports assigning values to a group of elements through slicing syntax
nums = [40, 36, 89, 2, 36, 100, 7]
# Amendment No 1~4 The value of the elements ( Excluding the 4 Elements )
nums[1: 4] = [45.25, -77, -52.5]
print(nums)
Python list (list) Provides index() and count() Method , They can all be used to find elements .
index() Method is used to find where an element appears in the list ( That's the index ), If the element doesn't exist , Will lead to ValueError error
index() The grammar format of is :
listname.index(obj, start, end)
among ,listname Represents the name of the list ,obj Represents the element to find ,start Indicates the starting position ,end Indicates the end position .
start and end Parameter is used to specify the search range :
nums = [40, 36, 89, 2, 36, 100, 7, -20.5, -999]
# Retrieve all elements in the list
print( nums.index(2) )
# retrieval 3~7 Between the elements
print( nums.index(100, 3, 7) )
# retrieval 4 After the elements
print( nums.index(7, 4) )
# Retrieve a non-existent element
print( nums.index(55) )
count() Method is used to count the number of times an element appears in the list , The basic syntax is :
listname.count(obj)
among ,listname Represents the list name ,obj Represents the element to be counted .
If count() return 0, It means that the element does not exist in the list , therefore count() It can also be used to judge whether an element in the list exists .
nums = [40, 36, 89, 2, 36, 100, 7, -20.5, 36]
# Count the number of occurrences of elements
print("36 There is %d Time " % nums.count(36))
# Determine whether an element exists
if nums.count(100):
print(" List exists 100 This element ")
else:
print(" Does not exist in the list 100 This element ")
Another kind of sequential table is called tuple :tuple.tuple and list Very similar , however tuple Once initialized, it cannot be modified , For example, it also lists the names of students :
adopt ( ) After creating tuples , In general use = Assign it to a variable , The specific format is :
tuplename = (element1, element2, ..., elementn)
among ,tuplename Represents the variable name ,element1 ~ elementn Elements representing tuples .
One thing to note is that , When there is only one string type element in the tuple created , The element must be followed by a comma ,
# Add a comma at the end
a =("http://c.biancheng.net/cplus/",)
print(type(a))
print(a)
# No comma at the end
b = ("http://c.biancheng.net/socket/")
print(type(b))
print(b)
t = (1)
print(t)
t1 = (1,)
print(t1)
# Convert string to tuple
tup1 = tuple("hello")
print(tup1)
# Convert the list to tuples
list1 = ['Python', 'Java', 'C++', 'JavaScript']
tup2 = tuple(list1)
print(tup2)
# Convert dictionary to tuple
dict1 = {
'a':100, 'b':42, 'c':9}
tup3 = tuple(dict1)
print(tup3)
# Convert an interval to a tuple
range1 = range(1, 6)
tup4 = tuple(range1)
print(tup4)
# Create an empty tuple
print(tuple())
Just like the list , We can use index (Index) Access an element in a tuple ( What we get is the value of an element ), You can also use slices to access a set of elements in a tuple ( What you get is a new sub tuple ).
tuplename[i]
#i Indicates the index value . The index of a tuple can be a positive number , It can also be negative .
tuplename[start : end : step]
#start Indicates the starting index ,end Indicates end index ,step Indicating step size .
url = tuple("http://c.biancheng.net/shell/")
# Use an index to access an element in a tuple
print(url[3]) # Use positive index
print(url[-4]) # Use negative index
# Use slices to access a set of elements in a tuple
print(url[9: 18]) # Use positive slices
print(url[9: 18: 3]) # Specify the step size
print(url[-6: -1]) # Use negative slices
We've already said , Tuples are immutable sequences , Elements in tuples cannot be modified , So we can only create a new tuple to replace the old tuple .
for example , Reassign tuple variables :
tup = (100, 0.5, -36, 73)
print(tup)
# Reassign tuples
tup = ('Shell Script ',"http://c.biancheng.net/shell/")
print(tup)
You can also connect multiple tuples ( Use + You can splice tuples ) Add a new element to the tuple , for example :
tup1 = (100, 0.5, -36, 73)
tup2 = (3+12j, -54.6, 99)
print(tup1+tup2)
print(tup1)
print(tup2)
When the tuple created is no longer used , Can pass del Keyword delete it , for example :
tup = ('Java course ',"http://c.biancheng.net/java/")
print(tup)
del tup
print(tup)
Python Dictionaries (dict) It's a kind of disorder 、 A variable sequence , Its elements are “ Key value pair (key-value)” Form storage of . relatively , list (list) And a tuple (tuple) They're all ordered sequences .
Python Dictionary features :
Because every element in the dictionary contains two parts , It's the key (key) And the value (value), So when you create a dictionary , Use colons between keys and values : Separate , Use commas between adjacent elements , Separate , All elements in braces { } in .
Use { } The syntax for creating a dictionary is as follows :
dictname = {
'key':'value1', 'key2':'value2', ..., 'keyn':valuen}
among dictname Represents the dictionary variable name ,keyn : valuen Represents the key value pairs of each element . It should be noted that , Each key in the same dictionary must be unique , Can't repeat .
# Use a string as key
scores = {
' mathematics ': 95, ' English ': 92, ' Chinese language and literature ': 84}
print(scores)
# Use tuples and numbers as key
dict1 = {
(20, 30): 'great', 30: [1,2,3]}
print(dict1)
# Create an empty tuple
dict2 = {
}
print(dict2)
Python in , You can also use dict Dictionary type provides fromkeys() Method to create a dictionary with default values , The specific format is :
dictname = dict.fromkeys(list,value=None)
among ,list Parameter represents a list of all keys in the dictionary (list);value The parameter indicates the default value , If you don't write , Is null None.
knowledge = [' Chinese language and literature ', ' mathematics ', ' English ']
scores = dict.fromkeys(knowledge, 60)
print(scores)
#str A key that represents a string type ,value Represents the value of the key . When creating a dictionary in this way , Strings cannot be quoted .
a = dict(str1=value1, str2=value2, str3=value3)
# towards dict() Function to pass in a list or tuple , And the elements in them contain 2 A list or tuple of elements , The first element is the bond , The second element is the value .
# The way 1
demo = [('two',2), ('one',1), ('three',3)]
# The way 2
demo = [['two',2], ['one',1], ['three',3]]
# The way 3
demo = (('two',2), ('one',1), ('three',3))
# The way 4
demo = (['two',2], ['one',1], ['three',3])
a = dict(demo)
# By applying the dict() Functions and zip() function , The first two lists can be converted into corresponding dictionaries .
keys = ['one', 'two', 'three'] # It can also be a string or a tuple
values = [1, 2, 3] # It can also be a string or a tuple
a = dict( zip(keys, values) )
Lists and tuples access elements through subscripts , The dictionary is different , It accesses the corresponding value through the key . Because the elements in the dictionary are out of order , The position of each element is not fixed , So dictionaries can't be like lists and tuples , Use slicing to access multiple elements at once .
Python The specific format of accessing dictionary elements is :
dictname[key]
among ,dictname Represents the name of a dictionary variable ,key Indicates the key name . Be careful , The bond must exist , Otherwise, an exception will be thrown .
tup = (['two',26], ['one',88], ['three',100], ['four',-59])
dic = dict(tup)
print(dic['one']) # Key exists
print(dic['five']) # The key doesn't exist
In addition to the above way ,Python More recommended dict Type provided get() Method to get the value corresponding to the specified key . When the specified key does not exist ,get() Method does not throw an exception .
get() The syntax format of the method is :
dictname.get(key[,default])
among ,dictname Represents the name of a dictionary variable ;key Indicates the specified key ;default When the key to be queried does not exist , The default value returned by this method , If you don't specify , Returns the None.
a = dict(two=0.65, one=88, three=100, four=-59)
print( a.get('one') )
a = dict(two=0.65, one=88, three=100, four=-59)
print( a.get('five', ' The key does not exist ') )
It's easy to add a new key value pair to the dictionary , Directly to the nonexistent key Assignment can , The specific syntax is as follows :
dictname[key] = value
a = {
' mathematics ':95}
print(a)
# Add a new key value pair
a[' Chinese language and literature '] = 89
print(a)
# Add new key value pair again
a[' English '] = 90
print(a)
Python The key in the dictionary (key) Cannot be changed , We can only modify the value (value).
The key of each element in the dictionary must be unique , therefore , If the key of the newly added element is the same as that of the existing element , Then the value corresponding to the key will be replaced by the new value
a = {
' mathematics ': 95, ' Chinese language and literature ': 89, ' English ': 90}
print(a)
a[' Chinese language and literature '] = 100
print(a)
If you want to delete the key value pairs in the dictionary , Still usable del sentence . for example :
# Use del Statement delete key value pair
a = {
' mathematics ': 95, ' Chinese language and literature ': 89, ' English ': 90}
del a[' Chinese language and literature ']
del a[' mathematics ']
print(a)
If you want to determine whether the specified key value pair exists in the dictionary , First, we should judge whether there are corresponding keys in the dictionary . Determine whether the dictionary contains the key for the specified key value pair , have access to in or not in Operator .
a = {
' mathematics ': 95, ' Chinese language and literature ': 89, ' English ': 90}
# Judge a Does it contain the name ' mathematics ' Of key
print(' mathematics ' in a) # True
# Judge a Whether to include the name ' Physics ' Of key
print(' Physics ' in a) # False
Put these three methods together to introduce , Because they are used to get specific data in the dictionary :
scores = {
' mathematics ': 95, ' Chinese language and literature ': 89, ' English ': 90}
print(list(scores.keys()))
print(scores.values())
print(scores.items())
copy() Method returns a copy of the dictionary , That is, return a new dictionary with the same key value pair , for example :
a = {
'one': 1, 'two': 2, 'three': [1,2,3]}
b = a.copy()
print(b)
update() Method can use the key value pairs contained in a dictionary to update the existing dictionary .
In execution update() When the method is used , If the updated dictionary already contains the corresponding key value pair , So the original value Will be covered ; If the updated dictionary does not contain the corresponding key value pair , Then the key value pair is added .
a = {
'one': 1, 'two': 2, 'three': 3}
a.update({
'one':4.5, 'four': 9.3})
print(a)
pop() Used to delete the specified key value pair
a = {
' mathematics ': 95, ' Chinese language and literature ': 89, ' English ': 90, ' chemical ': 83, ' biological ': 98, ' Physics ': 89}
print(a)
a.pop(' chemical ')
print(a)
set and dict similar , It's also a group. key Set , But no storage. value. because key Can't repeat , therefore , stay set in , No repeat key.
In the same set , Only immutable data types can be stored , Including plastic surgery 、 floating-point 、 character string 、 Tuples , Can't store list 、 Dictionaries 、 Set these variable data types , otherwise Python The interpreter will throw TypeError error . for instance :
a={
{
'a':1}}
b={
[1,2,3]}
c={
{
1,2,3}}
print(a,b,c)
Immutable data types : plastic 、 floating-point 、 character string 、 Tuples
Variable data types : list 、 Dictionaries 、 aggregate
For immutable objects , Call any method of the object itself , It doesn't change the content of the object itself . contrary , These methods create new objects and return , such , It ensures that the immutable object itself is immutable
For mutable objects , such as list, Yes list To operate ,list The internal content will change , such as :
>>> a = ['c', 'b', 'a']
>>> a.sort()
>>> a
['a', 'b', 'c']
And for immutable objects , such as str, Yes str To operate :
>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a
'abc'
a = {
1,'c',1,(1,2,3),'c'}
print(a)
set1 = set("c.biancheng.net")
set2 = set([1,2,3,4,5])
set3 = set((1,2,3,4,5))
print("set1:",set1)
print("set2:",set2)
print("set3:",set3)
Because the elements in the set are unordered , So you can't use subscripts to access elements like lists .Python in , The most common way to access collection elements is to use a circular structure , Read out the data in the collection one by one .
a = {
1,'c',1,(1,2,3),'c'}
for ele in a:
print(ele,end=' ')
set Add elements to the collection , have access to set Type provided add() Method realization
It should be noted that , Use add() Method , It's just numbers 、 character string 、 Tuple or boolean type (True and False) value , Can't add list 、 Dictionaries 、 Collect this kind of variable data , otherwise Python The interpreter will report TypeError error . for example :
a = {
1,2,3}
a.add((1,2))
print(a)
a.add([1,2])
print(a)
Add elements from a list or collection to set1
>>> set1 = {
1,2,3}
>>> set1.update([3,4])
>>> set1
{
1,2,3,4}
a = {
1,2,3}
a.remove(1)
print(a)
a.remove(1)
print(a)
Delete elements randomly
set1 = {
"a",2,3}
a = set1.pop()
print(a,set1)