Understanding of the Python list

Source: Internet
Author: User
Tags throw exception python list

Create List sample_list = [' A ', 1, (' A ', ' B ')]

Python list Operation sample_list = [' A ', ' B ', 0,1,3]

Get a value in the 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 #will return a list [0,1,2,..., 29]

Initialize the list with a fixed value Initial_value = 0 List_length = 5 Sample_list = [Initial_value for i in range] sample_list = [Initial_val Ue]*list_length # sample_list ==[0,0,0,0,0]

Attached: Python built-in type 1, list: lists (i.e., dynamic array, C + + standard library vector, but can contain different types of elements in a list) a = ["I", "You", "he", "she"] # element can be any type.

Subscript: Read and write according to subscript, as array processing starting at 0, negative subscript using 0 first element, 1 last element,-len first element, len-1 the last element the number of elements of the 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]

List Methods L.append (Var)    #追加元素 L.insert (Index,var) L.pop (Var)       #返回最后一个元素, and remove it from List L.remove (Var)    #删除第一次出现的该元素 L.count (Var)     #该元素在列表中出现的个数 L.index (Var)      #该元素的位置, none throw exception   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]   #删除指定下标范围的元素 list Copy L1 = l      #L1为L的别名, in C is the same pointer address, the L1 operation is the operation of L. The function parameter is passed L1 = l[:]   #L1为L的克隆, another copy.          list Comprehension    [<expr1> for K in L if <expr2& Gt ]                  2, Dictionary: Dictionary (that is,C + + standard library map) 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)        # Same as Dict[key], more than one does not return the default value, 0. [] No then throw exception D.has_key (key)       #有该键返回TRUE, otherwise false d.keys ()              #返回字典键的列表 d.values () d.items ()

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

3, tuple: tuples (that is, constant array) tuple = (' A ', ' B ', ' C ', ' d ', ' e ') can be used to extract elements from the list's []: operator. Is that you cannot modify elements directly.

4, String: character (that is, cannot be modified list) str = "Hello My Friend" 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. Substring extraction 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 s.join (list, ') #将list转string, connected with a space

The built-in function for processing strings len (str) #串长度 cmp ("My Friend", str) #字符串比较. The first one is large, returning 1 max (' abcxyz ') #寻找字符串中最大的字符 min (' abcxyz ') #寻找字符串中最小的字符

The conversion of string, oat (str) #变成浮点数, the result of the float ("1e-1") is 0.1 int (str) #变成整型, and the Int ("12") result is an int (str,base) #变成b The number of ASE-binary integers, int ("11", 2) results in 2 long (str) #变成长整型, Long (str,base) #变成base进制长整型,

The formatting of the string (note its escape character, mostly as C, slightly) Str_format% (parameter list) #参数列表是以tuple的形式定义的, that is, cannot be changed >>>print ""%s ' s height is%dcm "% (" M Y brother ", 180cm) #结果显示为 My brother ' s height is

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

Mutual transformation of list and tuple

Tuple (LS) list (LS)

Understanding of the Python list

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.