>>> alist = [10, 5, 32, 1, 8, 20]
>>> alist[0] = 100
>>> alist[1:3] = [45, 88, 12, 24]
>>> alist
[100, 45, 88, 12, 24, 1, 8, 20]
>>> alist[2:2]
[]
>>> alist[2:2] = [12, 8]
>>> alist
[100, 45, 12, 8, 88, 12, 24, 1, 8, 20]
# List method
>>> alist.append(12) # Additional
>>> alist.extend([55, 32, 1]) # Join multiple
>>> alist.remove(8) # Remove the first one 8
>>> alist.index(12) # Return to the first 12 The subscript
>>> alist.reverse() # Flip
>>> blist = alist.copy() # take alist Value copy after , Assign a value to blist
>>> alist.insert(2, 88) # The subscript for 2 Insert at 88
>>> alist.sort() # Ascending order
>>> alist.sort(reverse=True) # Descending
>>> alist.count(12) # Statistics 12 Number of occurrences
>>> alist.pop() # Pop up the last item
>>> alist.pop(2) # The pop-up subscript is 2 Project
It is equivalent to a static list .
>>> atuple = (10, 20, 15)
>>> atuple.count(10) # Statistics 10 Number of occurrences
1
>>> atuple.index(15) # obtain 15 The subscript
2
>>> a = (10)
>>> type(a) <class 'int'>
>>> a
10
>>> b = (10,) # A single element tuple must have a comma
>>> type(b) <class 'tuple'>
>>> len(b)
1
practice : Simulation stack structure
(0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 2
[]
(0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 0
data : hello
(0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 0
data : world # Last in, first out ( What is written in is taken out first ) (0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 2 ['hello', 'world'] (0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 1
Pop out of the stack : world
(0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 2 ['hello'] (0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 1
Pop out of the stack : hello
(0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 1
Empty stack
(0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): 3
bye-bye
def push_it(): # Pressing stack
def pop_it(): # Out of the stack
def view_it(): # Inquire about
def show_menu(): # All other judgment statements that implement functions are summarized into one function
if __name__ == '__main__':
show_menu()
3. Write specific function statements in each function
The first method :
stack = []
def push_it():
data = input(' Please input data :').strip()
if data:
stack.append(data)
else:
print(' Data is empty , Not added ')
def pop_it():
if stack:
print(' Pop out of the stack : %s' % stack.pop())
else:
print(' Empty stack ')
def view_it():
print(stack)
def show_menu():
prompt = '''
(0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3):'''
while True:
choice = input(prompt).strip()
if choice not in ['0','1','2','3']:
print(' Invalid input , Please try again !')
continue
if choice == '0':
push_it()
elif choice == '1':
pop_it()
elif choice == '2':
view_it()
else:
print('Bye_bye')
break
if __name__ == '__main__':
show_menu()
The second method ( Using dictionaries ):
stack = []
def push_it():
data = input(' data : ').strip()
if data:
stack.append(data)
else:
print(' Data is empty , Not added ')
def pop_it():
if stack:
print(' Pop out of the stack : %s' % stack.pop())
else:
print(' Empty stack ')
def view_it():
print(stack)
def show_menu():
# Dictionaries are container types , Any object can be stored in , In this example, the function is stored
cmds = {'0': push_it, '1': pop_it, '2': view_it}
prompt = """(0) Pressing stack
(1) Out of the stack
(2) Inquire about
(3) sign out
Please select (0/1/2/3): """
while True:
choice = input(prompt).strip() # Remove the blank characters at both ends of the string
if choice not in ['0', '1', '2', '3']:
print(' Invalid input , Please try again . ')
continue
if choice == '3':
print('Bye-bye')
break
cmds[choice]() # Get the corresponding function from the dictionary and call it
if __name__ == '__main__':
show_menu()
>>> dict(['ab', ['name', 'bob'], ('age', 20)])
{'a': 'b', 'name': 'bob', 'age': 20}
>>> dict([('name', 'tom'), ('age', 20), ('mail', '[email protected]')])
{'name': 'tom', 'age': 20, 'mail': '[email protected]'}
>>> {}.fromkeys(['tom', 'jerry', 'bob'], 20)
{'tom': 20, 'jerry': 20, 'bob': 20}
>>> info = dict([('name', 'tom'), ('age', 20), ('mail', '[email protected]')])
>>> info
{'name': 'tom', 'age': 20, 'mail': '[email protected]'}
>>> for key in info:
... print(key, info[key])
...
name tom
age 20
mail [email protected]
>>> '%(name)s is %(age)s years old' % info
'tom is 20 years old'
>>> '%s is %s years old' % (info['name'], info['age'])
'tom is 20 years old'
>>> info['age'] = 22
>>> info['phone'] = '15012345678'
>>> info
{'name': 'tom', 'age': 22, 'mail': '[email protected]', 'phone': '15012345678'}
>>> 'tom' in info
False
>>> 'name' in info
True
>>> len(info) 4
>>> info.keys() # Take out all key
dict_keys(['name', 'age', 'mail', 'phone'])
>>> info.values() # Take out all value
dict_values(['tom', 22, '[email protected]', '15012345678'])
>>> info.items() # Take out the key value pair
dict_items([('name', 'tom'), ('age', 22), ('mail', '[email protected]'), ('phone',
'15012345678')])
>>> list(info.items()) # Turn key value pairs into lists
[('name', 'tom'), ('age', 22), ('mail', '[email protected]'), ('phone', '15012345678')]
>>> info.popitem() # Pop up an item in the dictionary
('phone', '15012345678')
>>> info.pop('mail') # eject key yes mail Project
>>> info.update({'mail': '[email protected]'}) # Update Dictionary
>>> {(1, 2): 'tom'} # Tuple as key
{(1, 2): 'tom'}
>>> {[1, 2]: 'tom'} # The list is variable , Can't be key, Report errors
# ** The most important method in the dictionary **
>>> info.get('name') # Take out from the dictionary key by name Value
'tom'
>>> print(info.get('phone')) # key Not in the dictionary , Default return None
None
>>> print(info.get('phone', 'not found')) # Can't find key return not found
not found
>>> info.get('name', 'not found')
'tom'
>>> print(info.get('phone', '110'))
110
Case study 2: Simulate user login information system
import getpass
userdb = {} # Used to store user name and password
def register():
username = input(' user name : ').strip()
if username == '':
print(' The username cannot be empty ')
elif not username.isalnum():
print(' The user name can only contain letters and numbers ')
elif username in userdb:
print(' The user already exists ')
else:
password = input(' password : ')
userdb[username] = password
def login():
username = input(' user name : ').strip()
password = getpass.getpass(' password : ').strip()
# if username not in userdb or userdb[username] != password:
if userdb.get(username) != password:
print('\033[31;1m Login failed \033[0m')
else:
print('\033[32;1m Landing successful \033[0m')
def show_menu():
cmds = {'0': register, '1': login}
prompt = """(0) register
(1) land
(2) sign out
Please select (0/1/2): """
while True:
choice = input(prompt).strip()
if choice not in ['0', '1', '2']:
print(' Invalid choice , Please try again . ')
continue
if choice == '2':
print('Bye-bye')
break
cmds[choice]()
if __name__ == '__main__':
show_menu()
verification :
# python 05.py
(0) register
(1) land
(2) sign out
Please select (0/1/2): 0
user name :lss
password :123
(0) register
(1) land
(2) sign out
Please select (0/1/2): 1
user name : lss
password :
Landing successful
(0) register
(1) land
(2) sign out
Please select (0/1/2): 2
Bye-bye
Set is a mathematical concept
>>> frozenset('abc') # Immutable set , Once the collection is created , You cannot add, delete, or modify
frozenset({'b', 'a', 'c'})
>>> set(['tom', 'jerry', 'bob'])
{'jerry', 'tom', 'bob'}
>>> aset = set('abc')
>>> bset = set('bcd')
>>> aset
{'b', 'a', 'c'}
>>> bset
{'b', 'd', 'c'}
>>> aset & bset # intersection , Elements in both sets
{'b', 'c'}
>>> aset | bset # Combine , All the elements in the two sets
{'b', 'd', 'a', 'c'}
>>> aset - bset # Differential complement ,aset There is ,bset No middle
{'a'}
>>> bset - aset # Differential complement ,bset There is ,aset No middle
{'d'}
>>> aset
{'b', 'a', 'c'}
>>> len(aset)
3
>>> 'a' in aset
True
>>> for ch in aset:
... print(ch)
>>> aset.add(10) # Add a new entry to the collection
>>> aset.pop() # Pop up any element
'b'
>>> aset.remove(10) # Delete the specified element
>>> aset.update(['tom', 'jerry', 'bob'])
>>> aset
{'tom', 'a', 'jerry', 'bob', 'c'}
>>> aset = set('abc')
>>> bset = set('bcd')
>>> aset.union(bset) # aset | bset
{'b', 'd', 'a', 'c'}
>>> aset.intersection(bset) # aset & bset
{'b', 'c'}
>>> aset.difference(bset) # aset - bset
{'a'}
>>> cset = aset.union(bset)
>>> aset.issubset(cset) # aset yes cset A subset of ?
True
>>> cset.issuperset(aset) # cset yes aset Super Collection of ?
True
# Collections are often used to implement de duplication operations
>>> from random import randint
>>> nums = [randint(1, 20) for i in range(20)]
>>> nums
[6, 12, 18, 19, 1, 1, 16, 15, 5, 6, 18, 19, 14, 11, 17, 13, 2, 5, 20, 16]
>>> result = []
>>> for i in nums:
... if i not in result:
... result.append(i)
>>> result
[6, 12, 18, 19, 1, 16, 15, 5, 14, 11, 17, 13, 2, 20]
>>> list(set(nums))
[1, 2, 5, 6, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
practice :
python l2w.py userdb.py => Generate new file , Already have windows The newline for
"""
Convert to windows Line feed format
Delete the blank characters at the end of each line in the source file , Put it together again \r\n
"""
----> The solution is linux Get the text file on windows It will be displayed in a line when the , No return , You need to convert the text file, that is
can .
import sys
def unix2dos(src, dst):
with open(src) as src_fobj:
with open(dst, 'w') as dst_fobj:
for line in src_fobj:
line = line.rstrip() + '\r\n'
dst_fobj.write(line)
if __name__ == '__main__':
unix2dos(sys.argv[1], sys.argv[2])