Go [Python] [List operation]

Source: Internet
Author: User
Tags python list

Create a list
Sample_list = [' A ', 1, (' A ', ' B ')]

Python list Operations
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
Del Sample_list[0]

Insert a value in the list
SAMPLE_LIST[0:0] = [' Sample value ']

Get the length of the list
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 (30)
#will return a list [0,1,2,..., 29]

Initialize a list with a fixed value
Initial_value = 0
List_length = 5
Sample_list = [Initial_value for i in range (10)]
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)
A = ["I", "You", "he", "she"] # elements can be of any type.

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], with no 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 removed from the list
L.remove (Var) #删除第一次出现的该元素
L.count (Var) #该元素在列表中出现的个数
L.index (Var) #该元素的位置, no exception thrown
L.extend (list) #追加list, that is, merge list to L
L.sort () #排序
L.reverse () #倒序
List operator:, +,*, Keyword del
A[1:] #片段操作符, for the extraction of 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. This is how the function arguments are passed.
L1 = l[:] #L1为L的克隆, that is, another copy.

List comprehension
[<expr1> for K in L if <expr2>]

2. Dictionary: Dictionary (Map of C + + standard library)
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.

dictionary method
D.get (key, 0)        #同dict [key], more than a default value, 0. [] No exception thrown
D.has_key (key)       #有该键返回TRUE, otherwise false
D.keys ()              #返回字典键的列表
D.values ()
D.items ()

D.update ( DICT2)      #增加合并字典
D.popitem ()          #得到一个pair, and remove it from the dictionary. Empty throws Exception
D.clear ()            #清空字典, same as Del dict
D.copy ()             #拷贝字典
d.cmp (dict1,dict2)   #比较字典, ( Priority is the number of elements, key size, key value size)
                     #第一个大返回1, small return-1, same as return 0
             
Dictionary copy
Dict1 = dict        #别名
dict2= Dict.copy ()    #克隆, another copy.

3, tuple: tuple (that is, a constant array)
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)
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
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-1
S.rfind (Substring,[start [, end]]) #反向查找
S.index (Substring,[start [, end]]) #同find, just can't find the resulting valueerror exception
S.rindex (Substring,[start [, end]]) #同上反向查找
S.count (Substring,[start [, end]]) #返回找到子串的个数

S.lowercase ()
S.capitalize () #首字母大写
S.lower () #转小写
S.upper () #转大写
S.swapcase () #大小写互换

S.split (str, ') #将string转list, with a space slice
S.join (list, ') #将list转string, with a space connection

Built-in functions for working with strings
Len (str) #串长度
CMP ("My Friend", str) #字符串比较. First large, returns 1
Max (' abcxyz ') #寻找字符串中最大的字符
Min (' abcxyz ') #寻找字符串中最小的字符

Conversion of String

Oat (str) #变成浮点数, float ("1e-1") results are 0.1
int (str) #变成整型, int ("12") result is 12
Int (str,base) #变成base进制整型数, int ("11", 2) result is 2
Long (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
>>>print ""%s ' height is%dcm "% (" My brother ", 180)
#结果显示为 My brother ' s height is 180cm

。。。。。。。。。。。。。。。。。。

Mutual transformation of list and tuple

Tuple (LS)
List (LS)

Go [Python] [List operation]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.