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")	# Add "b" after the 0th element, if changed to 1, it will be added after the 1st element
a.pop()	# Delete the last element by default
a.remove(1)	# Delete the first occurrence of 1
a.reverse()# Reverse the order
print(c)
print(a)
a_1=["a",1,9.9,True,None]
b_1 = a_1 # In Python, assigning directly creates a reference, b_1 and a_1 both point to the same value
# Using the .copy() function can make a_1 and b_1 print different values
b_1[0]="c"
print(a_1)
print(b_1) # It is found that only b is changed, and a is also changed unexpectedly

image.png

Dictionary#

a=dict(d=1,b=2,c=3)# Initialize the dictionary and establish key-value pairs
print(a["b"])# If there is b 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 tuples and lists is that once generated, they 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 seems to be able to default to the form of a

image.png

Traversing Object Collections#

The for loop can traverse 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 as 5, and then use the range() function to get the index of each length
    print(a[i])
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.