Part I day03 - tuples, dictionaries, strings

Posted by maddogandnoriko on Fri, 04 Oct 2019 21:27:43 +0200

The tuple
Tuple query
1 a = (1,2,3,4)
2 print(a[1:2]) #(2,)
Shopping cart exercise (list method exercise)
 1 product_list=[
 2     ['Mac',9000],
 3     ['kindle',800],
 4     ['tesla',900000],
 5     ['python book',105],
 6     ['bike',2000],
 7 ]
 8 pubs_list = []
 9 save = input("please input money:")
10 if save.isdigit():
11     save = int(save)
12     while True:
13 
14         print("shopping info".center(50,"-"))
15         #,Print the contents of the goods
16         for i,v in enumerate(product_list,1):
17             print(i,v)
18         choice = input("please input nums:")
19         #Verify that the input is legitimate
20         if choice.isdigit():
21             choice = int(choice)
22             if choice > 0 and choice <= len(product_list):
23                 #User Selection Commodity p_iters take out
24                 p_iters = product_list[choice-1]
25                 # print(p_iters)
26                 #If the remaining money is enough, you can continue to buy it.
27                 if p_iters[1] < save:
28                     pubs_list.append(p_iters)
29                     print(p_iters)
30                     save -= p_iters[1]
31                 else:
32                     print("Sorry, your credit is running low %s" % save)
33         elif choice == 'quit':
34             for j in pubs_list:
35                 # print(pubs_list)
36                 print("Goods you purchased :%s" % j)
37             print("Remaining amount of purchased goods :%s" % save)
38             break
39 
40         else:
41             print("Invalid input")

Dictionary

Dictionary: It is the only mapping type in Python. It stores data in the form of key-value pairs.
Features: 1. The dictionary is disordered, and the key can be hashed 2. The key is unique.

Invariant types: integers, strings, meta-ancestors
Variable Types: Lists, Dictionaries

Dictionary Creation
 1 a=list()  #List creation
 2 print(a) #[]
 3 
 4 dic={'name':'dream'}
 5 print(dic) #{'name': 'dream'}
 6 
 7 dic1={}
 8 print(dic1) #{}
 9 
10 dic2=dict((('name','dream'),))
11 print(dic2) #{'name': 'dream'}
12 
13 dic3=dict([['name','dream'],])
14 print(dic3) #{'name': 'dream'}
id method use
1 a = 100
2 print(id(a)) #94845938306592
3 b = a
4 print(id(b)) #94845938306592
5 b = 20
6 print(id(b)) #94457323938848
Dictionary increase
1 dic1 = {'name':'dream'}
2 print(dic1) #{'name': 'dream'}
3 #setdefault,The key exists and returns the corresponding value of the key you want to use.,Key does not exist, add a new key-value pair to the dictionary
4 ret = dic1.setdefault('age',20)
5 print(dic1)  #{'name': 'dream', 'age': 20}
6 print(ret) #20
Dictionary Query
1 dic2 = {'age': 20, 'name': 'dream'}
2 print(dic2['name']) #dream
Display all keys in the list
1 print(dic2.keys()) #dict_keys(['age', 'name'])
2 print(list(dic2.keys())) #['name', 'age']
3 #Display the values stated in the list
4 print(list(dic2.values())) #[20, 'dream']
5 #Key and Value Said in Display List
6 print(list(dic2.items())) #[('name', 'dream'), ('age', 20)]
Dictionary modification
1 dic3 = {'age': 20, 'name': 'dream'}
2 dic3['name'] = 'rise'
3 print(dic3) #{'name': 'rise', 'age': 20}
4 #update
5 dic4 = {'age':18,'sex':'man'}
6 dic3.update(dic4)
7 print(dic3) #{'age': 18, 'sex': 'man', 'name': 'rise'}
Dictionary deletion
 1 dic5 = {'age': 18, 'sex': 'man', 'name': 'rise'}
 2 
 3 #del Delete key-value pairs
 4 del dic5['age']
 5 print(dic5) #{'sex': 'man', 'name': 'rise'}
 6 #clear Empty dictionary
 7 dic5.clear()
 8 print(dic5) #{}
 9 
10 #pop Delete the specified key-value pair in the dictionary and return the value of the key-value pair
11 ret = dic5.pop('name')
12 print(ret) #rise
13 print(dic5) #{'sex': 'man', 'age': 18}
14 #popitem Randomized deletion of a set of key-value pairs, disease returns the value as a meta-ancestor
15 ret = dic5.popitem()
16 print(ret) #('sex', 'man')
17 print(dic5) #{'name': 'rise', 'age': 18}
18 #Delete the whole dictionary
19 del dic5
20 print(dic5)
Dictionary initialization
1 dic6 = dict.fromkeys(['age', 'sex','name','rise'],'test')
2 print(dic6) #{'rise': 'test', 'sex': 'test', 'age': 'test', 'name': 'test'}
Dictionary nesting
1 school = {
2     "teachers":{
3         'xiaowang':["Tall person","Long handsome"],
4         'xiaohu':["Good technology","Good play"]
5     },
6     "students":{
7         "zhangsan":["Good grades","Love to tell jokes"]
8     }
9 }
Dictionary Nested Query
1 print(school['teachers']['xiaohu'][0]) #Good technology
2 print(school["students"]["zhangsan"][1]) #Love to tell jokes
Dictionary Nested Modification
1 school["students"]["zhangsan"][0] = "The eyes look good."
2 print(school["students"]["zhangsan"][0]) #The eyes look good.
Dictionary ranking
1 dic = {6:'666',2:'222',5:'555'}
2 print(sorted(dic)) #[2, 5, 6]
3 print(sorted(dic.values())) #['222', '555', '666']
4 print(sorted(dic.items())) #[(2, '222'), (5, '555'), (6, '666')]
Cyclic traversal
1 dic7 = {'name': 'rise', 'age': 18}
2 for i in dic7:
3     print(("%s:%s") % (i,dic7[i])) #name:rise age:18

String
 1 a = "this is my progect"
 2 #Repeated output string
 3 print(a*2) #Repeat twice this is my progectthis is my progect
 4 #Getting strings by index
 5 print(a[3:]) #s is my progect
 6 #in Method discrimination
 7 print('is' in a) #True
 8 #Format output string
 9 print('%s mode1' % a) #this is my progect mode1
10 
11 #String splicing
12 a = "this is my progect"
13 b = "test"
14 print("".join([a,b])) #this is my progecttest
15 
16 d = "this is my progect"
17 e = "test"
18 f = ""
19 print(f.join([d,e])) #this is my progecttest
20 
21 #Common built-in methods for Strings
22 a = "this is my progect"
23 #Centered display
24 print(a.center(50,'*')) #****************this is my progect****************
25 #Number of repetitions of statistical elements in strings
26 print(a.count("is")) #2
27 #title case
28 print(a.capitalize()) #This is my progect
29 #End with something
30 print(a.endswith("ct")) #True
31 #Start with something
32 print(a.startswith("th")) #True
33 #Adjust the number of spaces
34 a = "this\t is my progect"
35 print(a.expandtabs(tabsize=10)) #this       is my progect
36 #Find an element and return the index value of the element
37 a = "this is my progect"
38 print(a.find('is')) #2
39 a = "this is my progect{name},{age}"
40 print(a.format(name='dream',age=18)) #this is my progectdream,18
41 print(a.format_map({'name':'rise','age':20})) #this is my progectrise,20
42 print(a.index('s')) #3
43 #Include numbers when judging strings
44 print("abc1234".isalnum()) #True
45 #Check for numbers
46 print('12345'.isdigit())#True
47 #Check the validity of strings
48 print('123abc'.isidentifier()) #False
49 print(a.islower()) #True Judge whether it is all lowercase
50 print(a.isupper())
51 print('f    d'.isspace()) #Does it contain spaces?
52 print("My Project".istitle()) #title case True
53 print('my project'.upper()) #MY PROJECT
54 print('my project'.lower()) #my project
55 print('My project'.swapcase()) #mY PROJECT
56 print('my project'.ljust(50,"-")) #my project----------------------------------------
57 print('my project'.rjust(50,'-')) #----------------------------------------my project
58 #RemoveString spaces and newline characters
59 print("     my project\n".strip()) #my project
60 print('test')
61 #replace
62 print("my project project".replace('pro','test',1)) #my testject project
63 #Look from right to left
64 print("my project project".rfind('t')) #17
65 #Separation on the Right
66 print("my project project".rsplit('j',1)) #['my project pro', 'ect']
67 print("my project project".title()) #My Project Project

Topics: Python Mac