Python list array Usage instance resolution

Source: Internet
Author: User
This article describes in detail the Python list array usage in the form of an instance. Share to everyone for your reference. Specific as follows:

The list in Python is similar to a mutable array (ArrayList) in C # for sequential storage structures.

Create a list
The code is as follows:

Sample_list = [' A ', 1, (' A ', ' B ')]


Python list Operations

The code is as follows:

Sample_list = [' A ', ' B ', 0,1,3]


To get a value from a list

The code is as follows:

Value_start = sample_list[0]  end_value = sample_list[-1]



Delete the first value of a list

The code is as follows:

Del Sample_list[0]



Insert a value in the list


The code is as follows:

SAMPLE_LIST[0:0] = [' Sample value ']


Get the length of the list

The code is as follows:

List_length = Len (sample_list)


List traversal

The code is as follows:

For element in Sample_list:  print (Element)



Python list advanced Operations/Tips

Produces a numeric increment list

The code is as follows:

Num_inc_list = Range (  #will return a list [0,1,2,..., 29]


Initialize a list with a fixed value

The code is as follows:

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 (that is, dynamic arrays, C + + standard library vector, but can contain different types of elements in a list)

The code is 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

The code is as follows:

Len (list)   #list的长度. The actual method is the __len__ (self) method that called the object.


Create a continuous list

The code is as follows:

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

The code is as follows:

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, merge list to L on L.sort ()        #排序L. Reverse ()     #倒序

List operator:, +,*, Keyword del

The code is as follows:

A[1:]       #片段操作符, for 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

The code is as follows:

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. List comprehension[<expr1> for k in L if <expr2>]


2. Dictionary: Dictionary (Map of C + + standard library)

The code is 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

The code is as follows:

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

The code is as follows:

Dict1 = dict        #别名dict2 =dict.copy ()   #克隆, or another copy.



3, tuple: tuple (that is, a constant array)

The code is 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)

The code is 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

The code is as follows:

Str[:6]

string contains the judgment operator: In,not in

The code is as follows:

"He" in str "she" is not in Str


The string module also provides a number of methods, such as

The code is as follows:

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

The code is as follows:

Len (str)                #串长度cmp ("My Friend", str)   #字符串比较. First large, return 1max (' abcxyz ')           #寻找字符串中最大的字符min (' abcxyz ')           #寻找字符串中最小的字符string的转换oat (str) #变成浮点数, float ("1e-1″) The  result is 0.1int (str)        #变成整型, the  int ("12″)  result is 12int (str,base)   #变成base进制整型数, and the Int (" 11″,2) result is 2long ( STR)       #变成长整型, Long (str,base)  #变成base进制长整型,



Formatting of strings (note their escape characters, mostly C-language, slightly)

The code is as follows:

Str_format% (parameter list) #参数列表是以tuple的形式定义的, i.e. cannot be changed >>>print ""%s ' height is%dcm "% (" my brother ", #结果显示为 my bro Ther ' s height is 180cm



Mutual transformation of list and tuple

The code is as follows:

Tuple (LS) list (LS)



Python removes duplicate elements from list

The code is as follows:

A = [3, 3, 5, 7, 7, 5, 4, 2]a = List (set (a)) # [2, 3, 4, 5, 7] even sort all done.

Above is the Python list array usage instance parsing content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.