There are three built-in data structures in Python-lists, tuples, and dictionaries.
1) lists list [,]
A list is a sequence of
Shoplist = [' Apple ', ' carrot ', ' banana ']
Print shoplist #[' apple ', ' carrot ', ' banana '
Shoplist.append (' orange ') #末尾加入一个
Print shoplist #[' apple ', ' carrot ', ' banana ', ' orange ']
Shoplist.insert (2, ' Flint ') #指定位置插入
Print shoplist #[' apple ', ' carrot ', ' flint ', ' banana ', ' orange '
Shoplist.reverse () #反转
Print shoplist #[' orange ', ' banana ', ' flint ', ' carrot ', ' apple '
Shoplist.pop () #默认从末尾删除
Print shoplist #[' orange ', ' banana ', ' flint ', ' carrot ']
Shoplist.sort () #正向排序
Print shoplist #[' banana ', ' carrot ', ' flint ', ' orange ']
Del shoplist[1] #指定位置删除, equal to Shoplist.pop (1)
Print shoplist #[' banana ', ' flint ', ' orange ']
Shoplist.extend ([' Database ', ' egg ']) #末尾加入多个
Print shoplist #[' banana ', ' flint ', ' orange ', ' database ', ' egg ']
Shoplist.remove (' banana ') #删除指定项
Print shoplist #[' flint ', ' orange ', ' database ', ' egg ']
Get complete knowledge through Help (list).
List parsing expressions
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]
Working with large matrices using open source NumPy systems
Nesting 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]
List parsing
>>> list (map (sum, M)) #[6, 15, 24]
>>> {sum (row) for row in M} #set ([24, 6, 15])
Index operator
Index operator, subscript operation, starting from 0, supports reverse indexing, 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 '
Slice operator X[i:j]
Slice (slice) operator, with a sequence name followed by square brackets, with a pair of optional digits in square brackets, separated by a colon. The number is optional, and the colon is required.
X[I:J], remove the contents of X from offset to I, until but not including J
>>> 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[1:3] # WA, excluding r!
>>> name[2:] # Aroop
>>> Name[1:-1] # Waroo
>>> name[:] # Swaroop
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
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 ']
If you want to copy a list or a sequence or an object, you must use the slice operator to get the copy. Remember that the assignment statement for the list does not create a copy
Shallow copy deep copy
Shallow copy (1) Full slice operation [:];(2) Use the copy function of the copy module using factory functions such as List (), Dict ();(3)
Deep Copy (1) using the Deepcopy () function of the copy module
Simulating stacks
stack = []
Def pushit ():
Stack.append (Raw_input ("Enter new String:"). Strip ())
Def popit ():
If Len (stack) = = 0:
print ' Can not pops from an empty stack! '
Else
print ' Removed [', stack[-1], '] '
Stack.pop ()
Def viewstack ():
Print Stack
CMDs = {' U ':p ushit, ' o ':p opit, ' 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
if __name__ = = ' __main__ ':
2) tuples tuple (,)
Tuples are immutable and cannot be modified. Tuples are defined by a comma-separated list of items 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 use of tuples is in the print statement
Age = 22
name = ' Swaroop '
Print '%s is%d years old '% (name, age)
The print statement uses the string of the item tuple followed by the% symbol. The custom output satisfies a particular format. The customization can be%s to represent a string or%d to represent an integer.
3) Dictionaries dictionary {k:v}
Key-value pairs: 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.keys () #[' age ', ' job ', ' name ']
Print rec.values () #[40.5, [' Dev ', ' Mgr ', ' janitor '], {' 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])
Missing Key:
>>> value = D.get (' x ', 0)
>>> value #0
>>> value = d[' x '] if ' x ' in D else 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 a complete list of methods for the Dict class.
4) Set Set ()
A = set (' Abracadabra ')
b = Set (' Alacazam ')
Y = {' h ', ' A ', ' m '} #python3
Print a # unique letters in a
Print A-B # letters in A and not
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 and not both
Python tutorial seventh chapter, data structure