Python tutorial chapter 7, data structure, python Chapter 7
Python has three built-in data structures: List, tuples, and dictionary.
1) Lists List [,]
A list is a sequence.
shoplist = ['apple', 'carrot', 'banana']
print shoplist #['apple', 'carrot', 'banana']
Shoplist. append ('Orange ') # Add
print shoplist #['apple', 'carrot', 'banana', 'orange']
Shoplist. insert (2, 'flint') # insert at the specified position
print shoplist #['apple', 'carrot', 'flint', 'banana', 'orange']
Shoplist. reverse () # reverse
print shoplist #['orange', 'banana', 'flint', 'carrot', 'apple']
Shoplist. pop () # delete from the end by default
print shoplist #['orange', 'banana', 'flint', 'carrot']
Shoplist. sort () # forward sorting
print shoplist #['banana', 'carrot', 'flint', 'orange']
Del shoplist [1] # delete at the specified position, which is equal to shoplist. pop (1)
print shoplist #['banana', 'flint', 'orange']
Shoplist. extend (['database', 'egg']) # add multiple
print shoplist #['banana', 'flint', 'orange', 'database', 'egg']
Shoplist. remove ('banana ') # delete a specified item
print shoplist #['flint', 'orange', 'database', 'egg']
Use help (list) to obtain complete knowledge.
List parsing expression
Export a new list from an existing list.
vec = [2, 4, 6]
print (3 * x for x in vec) #<generator object <genexpr> at 0x00E7D300>
print list(3 * x for x in vec) #[6, 12, 18]
print [3 * x for x in vec] # [6, 12, 18]
print [3 * x for x in vec if x > 3] # [12, 18]
print [3 * x for x in vec if x < 2] # []
print [[x, x**2] for x in vec] # [[2, 4], [4, 16], [6, 36]]
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print [row[1] for row in M] # [2, 5, 8]
print [row[1] for row in M if row[1] % 2 == 0] #[2, 8]
print [x + y for x in 'abc' for y in 'mn'] #['am', 'an', 'bm', 'bn', 'cm', 'cn']
Use the open-source NumPy system to process large Matrices
Nesting
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print M #[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print M[0] #[1, 2, 3]
print M[1][2] #6
List Parsing
>>> list(map(sum, M)) #[6, 15, 24]
>>> {sum(row) for row in M} #set([24, 6, 15])
>>> {x: ord(x) for x in 'spabm'} #{'a': 97, 'p': 112, 's': 115, 'b': 98, 'm': 109}
Index Operator
Index operator, subscript operation, starting from 0, supports reverse index, starting from-1
>>> sp = ['a', 'b', 'c', 'd']
>>> sp[0], sp[1], sp[2], sp[3] #('a', 'b', 'c', 'd')
>>> sp[-4], sp[-3], sp[-2], sp[-1] #('a', 'b', 'c', 'd')
>>> name = 'swaroop'
>>> len(name) #7
>>> name[-1] #'p'
>>> name[len(name) - 1] #'p'
Slice operator X [I: J]
Slice operator, sequence name and square brackets, which contain an optional number and are separated by a colon. Numbers are optional, while colons are required.
X [I: J], which is taken from offset to I in X until the content of J is not included.
>>> shoplist = ['a', 'b', 'c', 'd']
>>> shoplist[1:3] #['b', 'c']
>>> shoplist[2:] #['c', 'd']
>>> shoplist[1:-1] #['b', 'c']
>>> shoplist[:] #['a', 'b', 'c', 'd']
name = 'swaroop'
>>> Name [] # wa, excluding r!
>>> name[2:] # aroop
>>> name[1:-1] # waroo
>>> name[:] # swaroop
>>> name * 2 # swaroopswaroop
Ternary slice operator X [I: J: K]
X[I:J] = X[I:J:1]
s = "abcdefghijklmn"
print s[1:10:2] #bdfhj
print s[::2] #acegikm
print s[::-2] #nljhfdb
Reference
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print shoplist # ['mango', 'carrot', 'banana']
print mylist # ['mango', 'carrot', 'banana']
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print shoplist # ['mango', 'carrot', 'banana']
print mylist # ['carrot', 'banana']
To copy a list, sequence, or object, you must use the slice operator to copy the object. Remember that the assignment statement of the list is not copied.
Deep copy
Shallow copy (1) Complete slicing operation [:]; (2) use factory functions, such as list () and dict (); (3) use the copy function of the copy Module
Deep copy (1) Use the deepcopy () function of the copy Module
Simulate Stack
stack = []
def pushit():
stack.append(raw_input("Enter new String:").strip())
def popit():
if len(stack) == 0:
print 'Can not pop from an empty stack!'
else:
print 'Removed [', stack[-1], ']'
stack.pop()
def viewstack():
print stack
CMDs = {'u':pushit, 'o':popit, 'v':viewstack}
def showmenu():
pr = """p(U)sh p(O)p (V)iew (Q)uit Enter choice:"""
while True:
while True:
try:
choice = raw_input(pr).strip()[0].lower()
except (EOFError, KeyboardInterrupt, IndexError):
choice = 'q'
print '\nYou picked: [%s]' %choice
if choice not in 'uovq':
print 'Invalid option, try again'
else:
break
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showmenu()
2) Tuples (,)
Tuples are unchangeable and cannot be modified. The tuples are defined by commas (,) in parentheses.
zoo = ('w', 'e', 'p')
new_zoo = ('m', 'd', zoo)
print zoo #('w', 'e', 'p')
print new_zoo #('m', 'd', ('w', 'e', 'p'))
print new_zoo[2] #('w', 'e', 'p')
print new_zoo[2][2] #p
new_zoo[1] = 'x' #TypeError: 'tuple' object does not support item assignment
The most common usage of tuples is to use them in print statements.
age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name
The print statement uses a string of the Project tuples followed by the % symbol. Custom output meets a specific format. The Value % s indicates a string or % d indicates an integer.
3) Dictionaries dictionary {k: v}
Key-Value Pair: d = {key1: value1, key2: value2}
rec = {'name': {'first': 'Bob', 'last': 'Smith'}, 'job': ['dev', 'mgr'], 'age': 40.5}
print rec['name'] #{'last': 'Smith', 'first': 'Bob'}
print rec['name']['last'] #'Smith'
print rec['job'] #['dev', 'mgr']
print rec['job'][-1] #'mgr'
rec['job'].append('janitor')
print rec #{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first': 'Bob'}}
print rec.keys() #['age', 'job', 'name']
print rec.values() #[40.5, ['dev', 'mgr', 'janitor'], {'last': 'Smith', 'first': 'Bob'}]
print rec.items() #[('age', 40.5), ('job', ['dev', 'mgr', 'janitor']), ('name', {'last': 'Smith', 'first': 'Bob'})]
Sorting Key:
>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> sorted(D) #['a', 'b', 'c']
D = {'a': 1, 'c': 3, 'b': 4}
for k in sorted(D.keys()): print(k, D[k])
for k in sorted(D): print(k, D[k]) #('a', 1) ('b', 4) ('c', 3)
Missing Key:
>>> value = D.get('x', 0)
>>> value #0
>>> value = D['x'] if 'x' in D else 0
>>> value #0
Other Ways
d = dict(zip(['a', 'b', 'c'], [1, 2, 3]))
print d # {'a': 1, 'c': 3, 'b': 2}
D = {c: c * 4 for c in 'SPA'}
print D #{'A': 'AAAA', 'P': 'PPPP', 'S': 'SSSS'}
Use help (dict) to view the complete list of dict classes.
4) set ()
a = set('abracadabra')
b = set('alacazam')
Y = {'h', 'a', 'm'} #python3
print a # unique letters in a
print a - b # letters in a but not in b
print a | b # letters in either a or b
print a & b # letters in both a and b
print a ^ b # letters in a or b but not both