x010

x010

厚积薄发

Data Structure Operations

List#

a=["a",1,9.9,True,None]
c=a[0] #Select the first element
1 in a #Check if 1 is in a
a.append(10)	#Add 10 to the end
a.insert(0,"b")	#Insert b after the 0th element; if changed to 1, it will insert b after the 1st element
a.pop()	#By default, remove the last element
a.remove(1)	#Remove the first occurrence of 1
a.reverse()#Reverse the list
print(c)
print(a)
a_1=["a",1,9.9,True,None]
b_1 = a_1 #In Python, assignment directly creates a reference; b_1 and a_1 both point to the same value
#Using the function .copy() allows a_1 and b_1 to print different values
b_1[0]="c"
print(a_1)
print(b_1)#Notice that changing b also changed a

image.png

Dictionary#

a=dict(d=1,b=2,c=3)#Initialize the dictionary to create key-value pairs
print(a["b"])#If b exists in dictionary a, then output it
if "c" in a:
    print(a["c"])
print(a.keys())#Get and output the keys in dictionary a
print(a.values())#Get and output the values in dictionary a
print(a.items())#Get key-value pairs and convert them to a list for output

image.png

Tuple#

The biggest difference between a tuple and a list is that once created, it cannot be changed.

a = ("1","2")#Generate and initialize using parentheses
x=tuple(["a","b","c"])#Initialize from a list using the tuple() function
b=("a",)#Even if there is only one, a comma must be added
c="a","b"#This format also seems to default to the tuple format

image.png

Iterating Over Collections#

A for loop can iterate over the above lists, dictionaries, and tuples.

a =["a",1,1.1,True,None]
for i in range(len(a)):  #Use the len() function to get the length of 5, then use the range() function to get each index of the length
    print(a[i])
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.