This example describes the Python list operation usage. Share to everyone for your reference, as follows:
List is one of the basic data structures in Python and is somewhat similar to ArrayList in Java, supporting the addition of dynamic elements. List also supports different types of elements in a list, list is an Object.
The most basic way to create a list
Copy the Code code as follows:
MyList = [' A ', ' B ', ' C ']
Python list common operations are as follows:
Create a list
Copy the Code code as follows:
Sample_list = [' A ', 1, (' A ', ' B ')]
Python list Operations
Copy the Code code as follows:
Sample_list = [' A ', ' B ', 0,1,3]
To get a value from a list
Value_start = Sample_list[0]end_value = Sample_list[-1]
Delete the first value of a list
Copy the Code code as follows:
Del Sample_list[0]
Insert a value in the list
Copy the Code code as follows:
SAMPLE_LIST[0:0] = [' Sample value ']
Get the length of the list
Copy the Code code as follows:
List_length = Len (sample_list)
List traversal
For element in Sample_list: print (Element)
Python list advanced Operations/Tips
Produces a numeric increment list
Num_inc_list = Range (#will return a list [0,1,2,..., 29]
Initialize a list with a fixed value
Initial_value = 0list_length = 5sample_list = [Initial_value for i in range]]sample_list = [initial_value]*list_length # sample_list ==[0,0,0,0,0]
Attached: Python built-in type
1, List: Lists (that is, dynamic arrays, C + + standard library vector, but can contain different types of elements in a list)
Copy the Code code as follows:
A = ["I", "You", "he", "she"] #元素可为任何类型.
Subscript: Read and write by subscript, as array processing
Starting with 0, negative subscript usage
0 first element, 1 last element,
-len first element, len-1 last element
Number of elements to fetch list
Len (list) #list的长度. The actual method is the __len__ (self) method that called the object.
Create a continuous list
L = range (1,5) #即 l=[1,2,3,4], excluding the last element L = Range (1, 2) #即 l=[1, 3, 5, 7, 9]
Method of List
L.append (Var) #追加元素L. Insert (Index,var) L.pop (Var) #返回最后一个元素 and remove L.remove (VAR) from List Deletes the first occurrence of the element L.count (Var) #该元素在列表中出现的个数L. Index (VAR) #该元素的位置, none throws the exception L.extend (list) #追加list, that is, merges list to L L.sort ( ) #排序L. Reverse () #倒序list operator:, +,*, keyword dela[1:] #片段操作符, for the extraction of the sub list [1,2]+[3,4] #为 [1,2,3,4]. with extend () [2]*4 #为 [2,2,2,2]del l[1] #删除指定下标的元素del L[1:3] #删除指定下标范围的元素
Copy of List
L1 = L #L1为L的别名, in C is the same pointer address, the L1 operation is the operation of L. The function parameter is the L1 = l[:] #L1为L的克隆, that is, another copy.
Copy the Code code as follows:
List comprehension
[ For k in L if ]
2. Dictionary: Dictionary (Map of C + + standard library)
Copy the Code code as follows:
Dict = {' Ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '}
Each element is a pair, containing the key, value two parts. Key is an integer or string type and value is any type.
The key is unique, and the dictionary only recognize the last assigned key value.
Methods of Dictionary
D.get (key, 0) #同dict [key], more than one does not return the default value, 0. [] No, throw exception D.has_key (key) #有该键返回TRUE, otherwise Falsed.keys () #返回字典键的列表D. VALUES () D.items () d.update (DICT2) # Add the merged dictionary D.popitem () #得到一个pair and remove it from the dictionary. Empty throws Exception D.clear () #清空字典, with del dictd.copy () #拷贝字典D. CMP (DICT1,DICT2) #比较字典, (priority is the number of elements, key size, key value size) #第一个大返回1, Small return-1, same as return 0
Replication of Dictionary
Dict1 = dict #别名dict2 =dict.copy () #克隆, or another copy.
3, tuple: tuple (that is, a constant array)
Copy the Code code as follows:
tuple = (' A ', ' B ', ' C ', ' d ', ' e ')
The element can be extracted with the [],: operator of list. Is that you cannot modify elements directly.
4, String: character (that is, a list of characters that cannot be modified)
Copy the Code code as follows:
str = "Hello My friend"
The string is a whole. If you want to modify a part of a string directly, it is not possible. But we can read a certain part of the string.
Extraction of substrings
Copy the Code code as follows:
Str[:6]
string contains the judgment operator: In,not in
"He" in Str
"She" not in Str
The string module also provides a number of methods, such as
S.find (substring, [start [, end]]) #可指范围查找子串, returns the index value, otherwise returns -1s.rfind (Substring,[start [, end]]) #反向查找S. Index (substring,[ Start [, end]]) #同find, just can't find the S.rindex (Substring,[start [, end]]) #同上反向查找S that produces the valueerror exception. Count (Substring,[start [, end]] ) #返回找到子串的个数S. Lowercase () s.capitalize () #首字母大写S. Lower () #转小写S. Upper () #转大写S. Swapcase () # Uppercase and lowercase s.split (str, ') #将string转list, with space s.join (list, ') #将list转string, connected with a space
Built-in functions for working with strings
Len (str) #串长度cmp ("My Friend", str) #字符串比较. First large, return 1max (' abcxyz ') #寻找字符串中最大的字符min (' abcxyz ') #寻找字符串中最小的字符
Conversion of String
Oat (str) #变成浮点数, the result of float ("1e-1") is 0.1int (str) #变成整型, the Int ("12") result is 12int (str,base) #变成base进制整型数, int ("11", 2) The result is 2long (str) #变成长整型, Long (str,base) #变成base进制长整型,
Formatting of strings (note their escape characters, mostly C-language, slightly)
Str_format% (parameter list) #参数列表是以tuple的形式定义的, i.e. cannot be changed in operation
Copy the Code code as follows:
>>>print ""%s ' height is%dcm "% (" My brother ", 180)
#结果显示为 My brother ' s height is 180cm
Mutual transformation of list and tuple
Tuple (LS) list (LS)
Add:
The list is also an object in Python, so he also has methods and properties that can be viewed in the Ptython interpreter using Help (list), some of which are open in the following way:
Here is an example code that describes the specific uses of these methods:
# coding=utf-8# filename:list.py# date:2012 11 20# Create a list mode heatlist = [' Wade ', ' James ', ' Bosh ', ' haslem ']tablelist = lis T (' 123 ') #list方法接受一个iterable的参数print ' Miami heat has ', Len (heatlist), ' NBA Stars, they is: ' #遍历list中的元素for player in heat List:print player, #向list添加元素heatList. Append (' Allen ') #方式一: Add parameters to the list end Objectprint ' \nafter Allen join the team, they is : ' Print Heatlistheatlist.insert (4, ' Lewis ') #方式二: Insert an element parameter one: Index position parameter two: Objectprint ' after Lewis join the team, they is: ' Print Heatlistheatlist.extend (tablelist) #方式三: Extension list, Parameters: iterable parameter print ' After extend a table List,now they is: ' Print Hea tlist# removes the element heatlist.remove (' 1 ') from the list #删除方式一: If the Parameter object has duplicate elements, only the top print "Remove ' 1" will be deleted. Now ' 1 ' is gone\n ", Heatlistheatlist.pop () #删除方式二: Pop optional parameter index deletes the element at the specified position by default to the last element print" Pop, "the previous element ' 3 ' \ n", Heatl Istdel Heatlist[6] #删除方式三: You can delete the development element or list slice print "Del ' 3 ' at the index 6\n", heatlist# logical Judgment # Statistic method count parameter: The value of the specific element print ' James AP Ears ', Heatlist.count (' Wade '), ' Times ' #in and not in print ' WAde in list? ', (' Wade ' in heatlist) print ' Wade not in list? ', (' Wade ' not in Heatlist) #定位 Index method: Parameter: The value of the specific element optional parameter: Slice range print ' Allen in the list? ' Heatlist.index (' Allen ') #下一行代码会报错 because Allen is not in the top three #print ' Allen in the fisrt 3 player? ', Heatlist.index (' Allen ', 0,3) #排序和反转代码print ' When the list was reversed: ' Heatlist.reverse () print Heatlistprint ' when the List is sorted: ' Heatlist.sort () #sort有三个默认参数 cmp=none,key=none,reverse=false so you can set the sorting parameters and then speak the shards of print heatlist#list [ Start:end] The element in the Shard that does not contain an end position print ' elements from 2nd to 3rd ', Heatlist[1:3]
I hope this article is helpful for Python program design.