Four types of data structures:
List = [Val1,val2,val3,val4]
Dictionary dict = {Key1:val1,key2:val2}
Tuple tuples = (VAL2,VAL2,VAL3,VAL4)
Set set = {Val1,val2,val3,val4}
One. List
The list can be loaded into all the objects in Python, examples
All_in_list = [
1, #整数
1.0 #浮点数
' A Worf ' #字符串
Print (), #函数
True, #布尔值
[#列表中套列表]
(), #元组
{' key ': ' Value '} #字典
]
Example 2 list additions and deletions
fruit = [' pineapple ', ' pear ']
Fruit.insert (1, ' Grape ')
Print (fruit)
Example 3 position insertion
FRUIT[0:0] = [' Orange ']
Print (fruit)
Example 3 the way to delete an element in a list is remove ():
Fruit = [' pinapple ', ' pear ', ' grape ']
Fruit.remove (' Grape ')
Print (fruit)
Example 4 replacing the element that modifies it
Fruit[0] = ' grapefruit '
Another way to delete del
Del Fruit[0:2]
Print (fruit)
Two. Dictionary (Dictionary)
Example
Nasdaq_code = {
' BIDU ': ' Baidu ',
' SINA ': ' SINA ',
' Yoku ': ' Youku ',
}
Search and delete of dictionaries
Add to
Nasdaq_code = {' BIDU ': ' Baidu ', ' SINA ': ' SINA '}
nasdaq_code[' yoku '] = ' Youku '
Print (Nasdaq_code)
The method extend () used to add multiple elements in the list also has a corresponding method for adding multiple elements in the dictionary update ():
Nasdaq_code.update ({' FB ': ' Facebook ', ' tsla ': ' Tesla '})
Delete the elements in the dictionary using the Del method:
Del nasdaq_code[' FB ']
Note that dictionaries are not allowed to be sliced.
Three. List of tuples in a stable version of tuple
Letters = (' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G ')
Letters[0]
Four. Set Set
You can judge the dependencies of the data by the collection, and sometimes you can subtract from the duplicated elements in the collection data structure.
Note that the collection cannot be sliced or indexed, and in addition to the set operation, the collection elements can be added and deleted:
A_set = {1,2,3,4}
A_set.add (5)
A_set.discard (5)
Five. Some tips for data structures
Ordinal arrangement
Num_list = [6,2,7,4,1,3,5]
Print (sorted (num_list))
Reverse order
Sorted (num_list,reverse=true)
At the same time, you need two lists to sort, you can use a zip function
For a, b in Zip (NUM,STR):
Print (b, ' is ', a)
Derivation formula
Put 10 elements into the list, common notation
A = []
For I in Range (1,11):
A.append (i)
List parsing methods
b = [I for I in Range (1,11)]
The list parsing is not only very convenient, but also much more efficient in execution than the former
Import time
A = []
T0 Time.clock ()
For I in Range (1,20000):
A.append (i)
Print ("Time.clock ()-T0,seconds process Time")
T0 = Time.clock ()
b = [I for I in Range (1,20000)]
Print ("Time.clock ()-T0,seconds process Time")
Get results
8.999999999998592e-06 seconds Process Time
0.0012320000000000005 seconds Process Time
A = [i**2 for i in Range (1,10)]
c = [j+1 for j in Range (1,10)]
K = [n for n in range (1,10) if n%2 = = 0]
z = [Letter.lower () for letter in ' ABCDEFGHIGKLMN ']
Dictionary derivation, satisfies the key-value two conditions to achieve:
D = {i:i+1 for i in range (4)}
g = {i:j for i,j in Zip (range (1,6), ' ABCDE ')}
g = {I:j.upper () for i,j in Zip (range (1,6), ' ABCDE ')}
Example
Letters = [' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G ']
For Num,letter in Enumerate (Letters):
Print (letter, "is", num+1)
The result is a=1,b=2 ...
Six. Integrated projects
Use the split method to separate each word in the string to get a separate word:
Lyric = ' The night begin to Shine,the night begin to Shine '
Words = Lyric.split ()
Results [' The ', ' Night ', ' begin ', ' to ', ' Shine ']
Word frequency statistics, the count method to count repeated occurrences of the words:
Path = '/users/hou/.../walden.txt '
With open (path, ' R ') as text:
Words = Text.read (). Split ()
print (words)
For word in words:
Print (' {}-{} times '. Format (Word,words.count (word)))
Result conclusion
1, some punctuation words are counted separately
2, some words show the number of occurrences more than once
3, because Python is case sensitive, the words that begin with uppercase are counted separately
Adjust the statistical methods and do some preprocessing on the words:
Import string
Path = '/userss/hou/.../walden.txt '
With open (path, ' R ') as text:
words = [Raw_word.strip (string.punctuation). Lower () for Raw_word in Text.read (). Split ()
Words_index = set (words)
For word in sorted (Counts_dict,key=lambda x:counts_dict[x],reverse=true):
Print (' {}--{} times '. Format (Word,counts_dict[word]))
The 1th line introduces a new module, string. In fact, the use of this module is very simple
String.punctuation print out, in fact, this is only contains all the punctuation [email protected]#$$%%%^&*
The 4th line, in the first paragraph of the text to remove the attached punctuation, and the first letter capitalized words into lowercase;
Line 5th, converts the list to a set function and automatically removes all duplicate elements
The 6th line creates a dictionary with the word key, which is the value of the occurrence frequency.
7–8, print the collated function, where Key=lambda x:counts_dict[x] is called a lambda expression and can be understood for a moment as a parameter sorted in a dictionary value
python-Data structure Data Structure1