The following editor will bring you a brief discussion on the common operations of lists, strings, and dictionaries in Python. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
The list operation is as follows:
a = ["haha","xixi","baba "]
Add: a.append[gg]
a.insert[1,gg] At the subscript 1, add gg
Delete: a. remove(haha) deletes the first matching haha from left to right in the list
del a.[0] deletes the value corresponding to the subscript 0
a.pop(0) in brackets If the content is not written, the last one will be deleted by default. If it is written, the content corresponding to the subscript will be deleted.
Change: a.[0] = "gg"
Check: a[0]
a.index("haha") displays the subscript of the first matching haha from left to right.
a.count("haha") displays the total number of haha in the list.
a. clear() clears the list a
Quickly traverses the contents of the list, removes subscripts, and prints them together.
enumerate(a) takes out each subscript and subscript content of the list and puts it into an array, so it can be traversed using a for loop.
a = ["haha","xixi","baba"]
for index,data in enumerate(a):print(index,":",data)
Result:
0 : haha
1 : xixi
2 : baba
##Key words:
a.copy() shallow copy, such as a = ["haha","xixi",["yan","liu"],"baba"]b = a.copy()
b = copy.deepcopy(a) deep, complete copy, b completely independent. But use sparingly. Because a separate memory space will be opened up. If the list a is large, this will consume a lot of memory.
String operations:
name = "The name is {name}, the age is {age}"print(name. capitalize()) #Capitalize the first letter
print(name.center(50,"-")) #Add 25 "-" to the left and right
print(name.endswith("an")) #Judge whether it is Ending with "an"
print(name.find("a")) #The subscript of the first "a" found from left to right
print(name.format(name="yan" ,age="24")) #Transform the content in the string {}
Dictionary operation:
Dictionary to obtain the value Method: a = {"yan":123,"liu":456}print(a["yan"]) #Method 1, if the key does not exist, an error will be reported
print (a.get("yanada")) #Method 2, if ket does not exist, return None
a.values() #Get value
*** serdefault usage:
print(a)
{ 'liu': 456, 'yan': 123}
a.setdefault("wang",789)
print(a)
{'yan': 123, 'liu': 456, 'wang ': 789}
*** Update usage:
b = {"yan":666,"haha":888}
a. update(b)
print(a)
{'yan': 666, 'haha': 888, 'liu': 456}
The above is the detailed content of Summary of common operations on lists, strings, and dictionaries in Python. For more information, please follow other related articles on the PHP Chinese website!