Reading catalogue
Introduction
2. Numbers
String
List
5. Yuan Zu
Dictionary
Seven. Collection
Summary of data types
Operator
Character Coding
11. Document Processing
Homework
# An Introduction
1 What is data?
x=10, 10 is the data we want to store
2 Why data should be classified into different types
Data is used to represent states, and different states should be represented by different types of data.
3 Data types
Numbers (shaping, long shaping, floating-point, complex)
String
Byte strings: Introducing bytes when introducing character encoding
List
Tuples
Dictionary
Collection
4. Learning data types according to the following points
#====================================== Basic use====================================== # 1. Use # 2. Definition # 3. Common Operations + Built-in Methods #====================================== Summary of this type==================================== # Save a value or store multiple values # Ordered or disordered # Variable or is immutable (1. Variable: value changes, id remains unchanged). Variable== not hash 2, immutable: the value changes, the id changes. Immutable = = hash)
2. Numbers
Shaping and Floating Point Type
# plastic(int) # ======================================Basic use====================================== # 1,purpose:Store mobile phone number, request number, ID number # 2,Definition # age = 18 # Create a new namespace in memory and store 18 in the namespace # Essence: Yes age = int(18) # s = '1.11' # res = int(s) # print(res) # s = '123' # res = int(s) # print(res) # # l = 'jasonascd123' # Conclusion: int Only digit strings can be dumped. float The decimal point can not be converted. # p = int(l) # print(p) # ValueError: invalid literal for int() with base 10: 'jasonascd123' # 3,Common Operations+Built-in method # ======================================Summary of this type==================================== # Shaping and Floating Point Save a Value # order # Invariant (1. Variable: Variable value, id Unchanged. variable==Must not hash 2,Invariant: Variable values. id Change. Immutable==can hash) """ //Variable type: value change, id unchanged, indicating that the original value is changed //Invariant type: Value change, id change means that a new memory space is reclaimed """ # float # Effect: salary = 1.11 # Essential salary = float(1.11) res = float('1.12345') print(res,type(res)) # 1.12345 <class 'float'>
# Conversion between binary, decimal, octal and hexadecimal systems
# Binary conversion: # Other Binary Conversion to 10 Binary # 1, binary conversion decimal 0, 1 # 10 # 1*(2**1) + 0*(2**0) >>>2 # 110 # 1*(2**2) + 1*(2**1) + 0*(2**0) >>>6 # 2. Octal conversion decimal 0,7"means that the maximum length is unlimited # 121: # 1*(8**2) + 2*(8**1) + 1*(8**0) >>>81 # 3. Hexadecimal conversion 10-ary 0-9 A-F # 216 # 2*(16**2) + 1*(16**1) + 6*(16**0) # print(int('1100', 2)) # Binary Conversion 10 # 1*(2**3)+1*(2**2) # print(int('14', 8)) # 1*(8**1) + 4 # print(int('c',16)) # 0-9 A-F
# A built-in method for converting decimal to other decimal
# A built-in method for converting decimal to other decimal # 1. > > 10 to binary print(bin(12)) # 0b1100Ob denotes that the following number is a binary number # 2. > > 10 to octal print(oct(12)) # 0o14 #The number after four represented by 0o is a binary number. # 2. > > 10-digit conversion to 16-digit print(hex(12)) # # 0xc 0x denotes that the following number is hexadecimal
# String
# Character string # ======================================Basic use====================================== # 1,Uses: Used to describe the content of things # 2,Definition: single quotation mark, double quotation mark and three quotation mark # 3,Common Operations+Built-in method # 1.Value by index (forward and reverse): only s = 'my baby' print(s[1]) # 2.Section # print(len(s)) # print(s[0:6:1]) # my bab String Index Slice Bone Sheath Regardless of Tail # print(s[0:-1]) # my bab # print(s[0:6:2]) # Step size is 2. Step size defaults to 1, which is equivalent to taking a value every other time. # # Understanding Negative Number Value # print(s[-1]) # Take the last one. # print(s[0:6:-2]) # This is paradoxical: 0:6 defaults from left to right - 2 from back to front # print(s[::-1]) # Reverse order ybab ym # print(s[6:0:-1]) # ybab y It is impossible to write without regard for the end.[0:6:-2] # print(s[-1:-6:-1]) # ,len():Statistics show that the number of strings contains spaces. # print(len(s)) # 7 # 4.Membership operation in or not in >>Judging that a substring exists in a large string # print('my' in 'my baby ') # True # print('a' in 'my baby') # True # print('koko' in 'my baby') # False # print('coco' not in 'my baby') # True # 5.Remove spaces strip() ,lstrip(),rstrip() # name = ' $$$$@##$$jason#@¥¥¥ ' # print(name.strip()) # print(name.lstrip()) # print(name) # print(name.strip()) # print(name) # name = '$$$@$$jason$$%$$$' # print(name.strip(' $@#¥')) # Just take the space and special characters and input them directly. # print(name.lstrip('$')) # Single Symbol Delete Left # print(name.rstrip('$')) # When encountering other symbols, stop directly to the right of deletion. # # 6. split Segmentation: A string is segmented for a segmented symbol, and the final segmented symbol is a list.,Symbols used for segmentation are removed. # l = 'jason|123|password|money' # res = l.split('|') # ['jason', '123', 'password', 'money'] # print(res) # # res1 = l.split('o',2) # Because the order of cutting is from left to right 2, the number of cuts can be made. # print(res1) # res2 =l.rsplit('o',1) # print(res2) # rspilt cuts strings from the left # 7.loop # for i in enumerate(l): # enumeration(0, 'j') The first is the index and the second is the corresponding element. # print(i) # ======================================Summary of this type==================================== # Save a value # order:Values that can be indexed are ordered types # Invariant (1. Variable: Variable value, id Unchanged. variable==Must not hash 2,Invariant: Variable values. id Change. Immutable==can hash)
# What needs to be mastered
# What needs to be mastered #1,strip,lstrip,rstrip # Remove spaces and special characters #2,lower,upper name = 'My loNe baBy' res = name.lower() # All in lowercase my lone baby print(res) res1 = name.upper() # All converted to lowercase MY LONE BAB print(res1) #3,startswith,endswith # What to begin with/end with is usually used to judge. l = 'jason is alxxoo' print(l.startswith('jason')) # True and False print(l.endswith('p')) # False One or more strings #4,format Three Plays # 1.Position by position and%s The principle is the same. # str1 = 'my name is {},my age is {}'.format('jason',18) # print(str1) # my name is jason,my age is 18 location is not specified to be interchangeable # 2.Pass values by index # str2 = 'my name is {0},my{1} age is {1}'.format('jason',18) # print(str2) # my name is jason,my18 age is 18 # 3.Keyword Reference(Identify by name the person) # str3 = 'my name is {name},my age is {age}'.format(name='jason',age=18) # print(str3) # my name is jason,my age is 18 {keywords must be specified} #5,split,rsplit #6,join # data = ['123','a','b','p'] # Containers must be of the same type before they can be stitched together # res = '@'.join(data) # print(res) # 123@a@b@p Splicing multiple elements of a container type into strings with specified symbols # res1 = '|'.join(data) # print(res1) # 123|a|b|p #7,replace replace # name = 'egon is very good' # res = name.replace('egon','jason',1) # print(res) # jason is very good #8,isdigit # Determine whether a string contains a stored number # while True: # pwd = input('>>>:').strip() # if pwd.isdigit(): # pwd = int(pwd) # print('yes') # break # else: # print('Not numbers') #
# Built-in methods that need to be understood
#1,find,rfind,index,rindex,count # name = 'egon is vTry gPod' # print(name.find('egon')) # Returns the index where the first first character resides. # print(name.find('en')) # -1 # # # rs = name.capitalize() # print(rs) # print(name.rfind('o')) # Start from the edge and find the first'o'Index 15 # print(name.find('e',1,3)) # -1 e The index of 0 is not error-free-1 # print(name.index('n',0,3)) # -1 Careful about one's head and disregarding one's tail # print(name.index('P')) # Case-sensitive # p = 'Dark clouds drift across the sky every day' # print(p.replace('cloud','Flaky clouds')) # replace # # print(p.count('day')) # Number of statistical occurrences #2,center,ljust,rjust,zfill # name = 'jason' # print(name.center(11,'*')) # The first parameter represents the total character length, and the second is what symbol is used to complete it. # # print(name.ljust(13,'$')) # Completion on the right side of the total number of z characters 13 #4,captalize,swapcase,title name = 'egon is vTry gPod' res = name.capitalize() print(res) # Egon is vtry gpod # Capitalize the first letter and turn the rest into lowercase res3 = name.swapcase() print(res3) # EGON IS VtRY GpOD Case interchange res4 = name.title() # Egon Is Vtry Gpod Capital letters for each word print(res4) #5,is Digital Series num1=b'4' #bytes num2=u'4' #unicode,python3 No need to add u Namely unicode num3='One' #Chinese Numbers num4='Ⅳ' #Roman numerals # ''.isnumeric(): unicode,Chinese Number, Roman Number Recognition of numbers as long as they represent them print(num2.isnumeric()) print(num3.isnumeric()) print(num4.isnumeric()) # ''.isdecimal(): unicode Recognize only ordinary Arabic numerals print(num2.isdecimal()) print(num3.isdecimal()) print(num4.isdecimal()) # ''.isdigit() :bytes,unicode Usually used isdigit You've already met your needs. print(num1.isdigit()) print(num2.isdigit()) print(num3.isdigit()) print(num4.isdigit())
# Write code,There are the following variables,Please implement each function as required (6 points, 0 for each sub-item).5 Points) name = " aleX" # 1) remove name Spaces on either side of the corresponding value of a variable,And output the processing results. # 2) judge name Does the value of a variable correspond to "al" Start,And output the results # 3) judge name Does the value of a variable correspond to "X" Ending,And output the results # 4) take name In the corresponding value of a variable“ l" Replace with“ p",And output the results # 5) take name The corresponding value of the variable is based on“ l" Division,And output the results. # 6) take name Variables correspond to capitalized values,And output the results # 7) take name Variables correspond to lower case values,And output the results # 8) Output please name The second character of the value corresponding to the variable? # 9) Output please name The first three characters of a variable's corresponding value? # 10) Output please name The last two characters of the corresponding value of a variable? # 11) Output please name Among the values corresponding to variables“ e" Location of index? # 12) Acquisition of subsequences,Remove the last character. as: oldboy Acquisition oldbo.
# Write code,There are the following variables,Please implement each function as required (6 points, 0 for each sub-item).5 Points) name = " aleX" # 1) remove name Spaces on either side of the corresponding value of a variable,And output the processing results. print(name.strip()) # 2) judge name Does the value of a variable correspond to "al" Start,And output the results print(name.startswith('al')) # False Spaces are also characters # 3) judge name Does the value of a variable correspond to "X" Ending,And output the results print(name.endswith('X')) # True # 4) take name In the corresponding value of a variable“ l" Replace with“ p",And output the results print(name.replace('l','p')) # Result: apeX # 5) take name The corresponding value of the variable is based on“ l" Division,And output the results. res = name.split('l') print(res) # [' a', 'eX'] l Removing comma separations between list elements returns # 6) take name Variables correspond to capitalized values,And output the results res1 = name.upper() print(res1) # ALEX # 7) take name Variables correspond to lower case values,And output the results res2 = name.lower() print(res2) # alex # 8) Output please name The second character of the value corresponding to the variable? print(name[1]) # 9) Output please name The first three characters of a variable's corresponding value? print(name[0:3]) # 10) Output please name The last two characters of the corresponding value of a variable? print(name[-2:]) # eX # 11) Output please name Among the values corresponding to variables“ e" Location of index? print(name.find('e')) # 3 # 12) Acquisition of subsequences,Remove the last character. as: oldboy Acquisition oldbo. print(name[0:-1])
# List: list
# ======================================Basic use====================================== # 1,purpose:The function is to store multiple values # 2,Definition:[] Elements in brackets are separated by commas, and elements can be of any type # The essence is name = list({'name':'jason','age':18}) # l = list({'name': 'jason', 'age': 18}) # print(l) # ['name', 'age'] Inside will be for Loop values, and then cram them into the list one by one # 3,Common Operations+Built-in method # Priority approach # 1.#1. Accessing values by index (forward access + reverse access): either stored or retrieved l = [1,2,3,4,5] print(l[0]) # print(l[1]) # print(l[3]) # print(l[::-1]) # Inverse reverse selection print(l[-1]) # 5 print(l[0:4:2]) # [1, 3] #Regardless of the end step size is the only default value # 2.Slices are careless# 3. Add Container Type Data# append# 1.Add a 666 element to the tail
# p.append(66) # What does not change the return value is the original value.
# print(p) # [11, 22, 33, 44, 55, 66]Direct addition of elements
# 2.Tail addition[88,99,00]
# p.append([88,99,69]) # Do not use variables to add values directly without returning values
# print(p) # [11, 22, 33, 44, 55, [88, 99, 69]] Adding the entire list as an element
# extend # Container type# extend # Container type
l.extend([11,22,33]) # The container type must be added
print(l) # [1, 2, 3, 4, 5, 11, 22, 33]
# insert# 3. Adding elements anywhere# l.insert(2,123) # Index location and insertion object
print(l) # [1, 2, 123, 3, 4, 5] Location in Index 2
l.insert(-2,8) # [1, 2, 3, 8, 4, 5] Support for negative addition
# l.insert(len(l),7) # Add at the end of [1, 2, 3, 4, 5, 7]
print(l)# 3.length
len(l)
# 4.Membership operation in/ not inres = 11 in p # True
print(22 not in p) # False
print(res)
# 5.delete remove
Keep in mind that there is no return value
del(l[2]) # Specified Index print(l)p = [11,22,33,44,55]
p.remove(55) # Delete elements directly
print(p) # [11, 22, 33, 44]res= l.pop(2) # Index deletion print(res)
hot water = l.pop()Default tail deletion for indexers not specified
# ======================================Summary of this type==================================== #
list Multiple values can be stored # order # Variable (1) Variable: Variable value; id Unchanged. variable==Must not hash 2,Invariant: Variable values. id Change. Immutable==can hash)
Supplementary: String splicing
#6,join
data = ['123','a','b','p'] # Containers must be of the same type before they can be stitched together
res = '@'.join(data)
Print (res) # 123@a@b@p splices multiple elements of the container type into strings with specified symbols
res1 = '|'.join(data)
print(res1,type(data),type(res1)) # 123|a|b|p <class 'list'> <class 'str'>
There are lists of data=['alex',49,[1900,3,18], and the names, ages, years of birth, months and days of birth in the list are assigned to different variables. 2. Simulate queues with lists 3. Simulate stacks with lists 4. For the following list, please rank by age (involving anonymous functions) l=[ {'name':'alex','age':84}, {'name':'oldboy','age':73}, {'name':'egon','age':18}, ] Answer: l.sort(key=lambda item:item['age']) print(l)