General description
Sequence: in Python, a sequence is a set of values [data set] arranged in order
There are three built-in sequence types in Python:
String, list, tuple
String operation
Advantages: supports indexing and slicing operations
Features: the first positive index is 0, the index points to the left end, and the first index is negative, pointing to the right end
Slice: [advanced features] can obtain any [part] data of sequence objects according to subscripts
Syntax structure: [start: end: step] step is 1 by default. If the slice exceeds the boundary, the slice will not report an exception
The intercepted content does not include the data corresponding to the end subscript
len(x) # string x characters
Capitalize (# initial capital)
Endswitch / startswitch() # end / start
find() # detects whether x is in the string
isalnum() # determines whether it is a number or a letter
isalpha() # determines whether it is a letter
isdigit() # determines whether it is the number 'abc123'. isdigit()
islower() # determines whether it is lowercase
join() # loop takes out all values and connects them with x
lower/upper() # case conversion
swapcase() # uppercase to lowercase, lowercase to uppercase
lstrip/rstrip/strip # remove left / right / both side blanks
split() # cut string
title() # capitalizes the first letter of each word
replace(old,new,count=None) #old: replaced string, new: replaced string, count: number of replaced strings. No count means to replace all
count() # counts the number of occurrences
# Test = 'Python' # print(type(Test)) # print("get first string% s"%Test[0]) # print("get second string% s"%Test[1]) # for item in Test: # print(item,end='') Test = 'helloworld' print("Test: %s"%Test) print("Test Memory address of:%d"%id(Test)) print("Test The first letter becomes uppercase:%s"%Test.capitalize()) #Initial capitalization print("Test Whether to H start:%s"%Test.startswith(' ')) #Start with x print("Test Whether to!end:%s"%Test.endswith('!')) #End x print("'o'stay Test Subscript in is:%s"%Test.find('o')) #Detect the position o in the string and return the subscript value. If it is not found, return - 1 print("'o'stay Test Subscript in is:%s"%Test.index('o')) #Detect the position o in the string and return the subscript value. If it is not found, an error will be reported print("Test Are they numbers or letters:%s"%Test.isalnum()) #Determine whether it is a number or a letter print("Test Is it a letter:%s"%Test.isalpha()) #Determine whether it is a letter print("Test Is it a number:%s"%Test.isdigit()) #Judge whether it is a number print("Test Is it lowercase:%s"%Test.islower()) #Judge whether it is lowercase # print("Cyclic extraction Test All values, with+connect:%s"%Test.join('+')) #Loop out all values and connect them with + print("Test Convert to uppercase:%s"%Test.lower()) #Convert to uppercase print("Test Convert to lowercase:%s"%Test.upper()) #Convert to lowercase print("Test Case conversion:%s"%Test.swapcase()) #Uppercase to lowercase, lowercase to uppercase print("remove Test Left margin:%s"%Test.lstrip()) #Remove left margin print("remove Test Right margin:%s"%Test.rstrip()) #Remove right margin print("remove Test Blank on both sides:%s"%Test.strip()) #Remove blank on both sides print("with'o'cutting Test:%s"%Test.split('o')) #Cut string print("Test Capitalize the first letter of each word:%s"%Test.title()) #Capitalize the first letter of each word # print("take Test in'!'Replace with'~':%s"%Test.replace('w','W',count=None)) #old: replaced string, new: replaced string, count: number of replaced strings. No count means to replace all print("Test in'o'Number of occurrences:%s"%Test.count('o')) #Count the number of occurrences print("output Test Third to fifth strings in:%s"%Test[3:6:1]) #Output the third to fifth strings in Test print("output Test Inverted string:%s"%Test[::-1])
List operation
Python is a very important data structure and an ordered data set
characteristic:
1. Add, delete, modify and query are supported
2. The data in the list can be changed [the data item can be changed, and the memory address will not be changed]
Note: any data type can be represented by [. 3] items in the list
4. Support indexing and slicing
Number of data items in len(x) # list x
append() # appends an element to the list
count() # counts the number of occurrences of the element
extend() # extension, equivalent to batch addition
index() # gets the index number of the specified element
insert() # inserts at the specified location
pop() # deletes the last element
remove() # removes the first element found on the left
reverse() # reverses the list
sort() # list sort reverse = True
li = [] li = [1,2,3,3,'Hello'] print("Length:%d"%len(li)) #Gets the number of objects in the list print("Type:%s"%type(li)) print("Content:%s"%li) #Output full list print("Output list elements with subscript 1:%s"%li[1]) #Output list elements with subscript 1 print("Output list elements of items 2 to 3:%s"%li[1:3]) #Output the second to third elements print("Reverse order output li Data items in the list:%s"%li[::-1]) #Output the data items of the li list in reverse order print("Output the data items in the list three times:%s"%(li*3)) #Output data items in the list three times [copy] print("stay Test Append element'7': %s"%li.append(789)) #Append element after list print(li) print("Statistics'3'stay Test Number of occurrences in:%s"%li.count(3)) #Counts the number of occurrences of the element print(li) print("extend Test: %s"%li.extend([456,789,369])) #Extension, equivalent to batch addition print(li) print("stay Test In, get'2'Index number of:%s"%li.index(2)) #Gets the index number of the specified element # index(x,start,end): find the subscript value of the data item x from the subscript start to end in the list print(li) print("stay Test Insert data item at position 3 in'99': %s"%li.insert(4,99)) #Insert 99 in position 4 print(li) li.pop() #pop(x): where x is the subscript of the data item and can be removed. It is the last element by default print("delete Test Result of the last element in:%s"%li) li.pop() print("delete Test Result of the last element in:%s"%li) li.pop() print("delete Test Result of the last element in:%s"%li) li.pop() print("delete Test Result of the last element in:%s"%li) li.pop() print("delete Test Result of the last element in:%s"%li) print("stay Test Remove the first element found on the left:%s"%li.remove(3)) #Remove the first element 3 found from the left print(li) print("reversal Test List:%s"%li.reverse()) #Reverse list print(li) print("yes Test Sort the list:%s"%li.sort()) #List sort reverse = True print(li)
Tuple operation
Is an immutable sequence that cannot be modified after creation
characteristic:
1. Immutable
2. Use () to create tuple types, and data items are separated by commas
3. It can be any type
4. When there is only one element in the tuple, add a comma, otherwise the interpreter will treat it as an integer
5. Slice operation can also be supported
# Tuple creation cannot be modified tupleA = () #Empty tuple # print(id(tupleA)) tupleA = ('abcd',89,9.12,'peter',[11,22,33]) # print(id(tupleA)) # print(type(tupleA)) # print(tupleA) # Tuple query # for item in tupleA: # print(item,end=' ') # pass # print(tupleA[2]) # print(tupleA[2:4]) # print(tupleA[::-1]) # print(tupleA[::-2]) # print(tupleA[-3:-1:]) #Element excluding - 1 # print(type(tupleA[0])) # tupleA[0] = '123' #FALSE # tupleA[4][0] = 9999 #You can modify the list type data in the tuple # print(tupleA[4]) # print(type(tupleA[4])) tupleB = (1) print(tupleB) print(type(tupleB)) tupleC = tuple(range(10)) print(tupleC) print(type(tupleC)) tupleD = (1,) #When there is only one data item in a tuple, a comma must be added after the data item print(tupleD) print(type(tupleD)) tupleE = (1,2,3,4,5,6,3,2,5,4,3,1) print(tupleE.count(3)) #Count the number of occurrences of 3
Dictionary operation
Python is a very important data structure that can store any object (a collection of key value pairs).
The {'key': 'value'} created by the dictionary in the form of key value pairs is wrapped in braces.
When finding an element in the dictionary, it is based on the key and value. Each element of the dictionary consists of two parts. Keys: Values
Key is usually used to access data (high efficiency). Like list, it supports the addition of data
The safe way to access the value is the get method. When we are not sure whether there is a key in the dictionary and want to obtain its value, we can use the get method and set the default value
be careful:
1. The key of the dictionary cannot be repeated, and the value can be repeated
2. Dictionary keys can only be immutable types, such as numbers, strings and tuples.
characteristic:
1. It is not a sequence type without the concept of subscript. It is an unordered key value collection and a built-in high-level type
2. Use {} to represent dictionary objects, and each key value pair is separated by commas (,)
3. The key must be of immutable type [tuple, string] and the value can be of any type
4. Each key must be unique. If there are duplicate keys, the latter will overwrite the former
Common methods:
1. Modify element: the value in the dictionary can be modified. Click to find the corresponding value and modify it
2. Add element: if the 'key' does not exist in the dictionary when using variable name ['key'] = data, this element will be added
3. Delete element: del deletes the specified element clear clears the dictionary
4. Count the number: len() can view several key value pairs in the dictionary
5. Get keys: Keys: return the dict keys object containing all the key values of the dictionary, and use the for loop to get each key value
6. Get value: Value: use values to return a dict values object containing all values
7. Get key value pairs: return a list dict items object containing all (key, value) tuples
8. Delete specified key: pop('key ') deletes the specified key
# How to create a dictionary from collections import defaultdict dictA = {'pro':'Everything is good and professional','school':'Everything is good school'} #Empty dictionary # print(id(dictA)) # print("the current dictionary length is:% d"%len(dictA)) dictA['name'] = 'Great beauty' dictA['age'] = '24' dictA['sex'] = 'female' # print("the current dictionary length is:% d"%len(dictA)) # print(id(dictA)) # print(type(dictA)) print(dictA) #Separated by commas # print(dictA['name']) #Get its value ('Big and beautiful ') through the key ('name') # print(dictA['age']) #Get its value through the key ('age ') (24) # print(dictA.get('name')) #Get its value ('Big and beautiful ') through the key ('name') # print(dictA.get('age')) #Get its value through the key ('age ') (24) # print(dictA.get('sex')) #Get its value ('female ') through the key ('sex') # print(dictA.get('pro')) #Get its value through the key ('pro ') (' everything is good, professional ') # print(dictA.get('school')) #Get its value through the key ('School ') ('everything is good school') # dictA['name '] =' Dashuai pot ' dictA.update({'name':'Dashuai pot'}) #If the executed key exists, modify it dictA.update({'hight':'1.80'}) #If the executed key does not exist, add it # print(dictA['name']) #Get its value ('Big and beautiful ') through the key ('name') #Get all keys # print(dictA.keys()) #Get all values # print(dictA.values()) #Get all key value pairs # print(dictA.items()) # for item in dictA.items(): # print(item) # for key,value in dictA.items(): # print('%s == %s'%(key,value)) #Delete operation # dictA.pop('hight') # print(dictA) # del dictA['pro'] # print(dictA) print(dictA) #How to sort Dictionaries print(sorted(dictA.items(),key=lambda d:d[0])) #Sort by key print(sorted(dictA.items(),key=lambda d:d[1])) #Sorting by value must be of the same type, otherwise it cannot be sorted
Common operation
Merge operation +: the addition of two objects will merge two objects
For strings, lists, tuples
Copy *: the object itself performs + operations for a specified number of times
For strings, lists, tuples
Judge whether the element exists in: (the return value is bool type)
Determines whether the specified element exists in the object
Applicable to strings, lists, tuples, dictionaries
#Common operation + * in # character string strA = 'Life is short' strB = 'Nothing' print(strA+strB) print(strA*5) print('living' in strA) print('people' in strB) #list listA = list(range(10)) listB = list(range(11,21)) print(listA+listB) print(listA*2) print(3 in listA) #tuple tupleA = [1,2,3] tupleB = [4,5,6] print(tupleA+tupleB) print(tupleA*3) print(2 in tupleA) print(2 in tupleB) #Dictionaries dictA = {'A':'a','B':'b'} print('A' in dictA.keys()) print('A' in dictA.values())