Python List Operational Usage Summary __python

Source: Internet
Author: User
Tags extend throw exception python list
This article mainly introduced the Python list operation usage, in the example form more detailed analysis of Python list of various common functions and the use of the method, the need for friends can refer to the

This example describes the Python list operation usage. Share to everyone for your reference, specific as follows:

The list is one of the basic data structures in Python, similar to the ArrayList in Java, and supports the addition of dynamic elements. The list also supports different types of elements in a list, the list is an Object.

The most basic way to create a list
Copy code code as follows: MyList = [' A ', ' B ', ' C ']

The Python list common operations are as follows:

Create a list
Copy code code as follows: Sample_list = [' A ', 1, (' A ', ' B ')]

Python list Operations
Copy code code as follows: Sample_list = [' A ', ' B ', 0,1,3]

Get one of the values in the list

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

Deletes the first value of a list
Copy code code as follows: Del Sample_list[0]

Insert a value in the list
Copy code code as follows: sample_list[0:0] = [' Sample value ']

Get the length of the list
Copy 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 list of numeric increments

Num_inc_list = Range
#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 (Ten)]
sample_list = [Initial_val Ue]*list_length
# sample_list ==[0,0,0,0,0]

attachment: Python built-in type

1, List: Lists (that is, dynamic array, C + + standard library vector, but can contain different types of elements in a list)
Copy code code as follows: a = ["I", "You", "he", "she"] #元素可为任何类型.

Subscript: Read and write by subscript, treated as an array
Starting with 0, the use of negative subscript
0 first element,-1 last element,
-len the first element, len-1 the last element

Number of elements to take list

Len (list) #list的长度. The actual method is to invoke the __len__ (self) method of this object.

Create a contiguous list

L = range (1,5)   #即 l=[1,2,3,4], excluding the last element
L = range (1, 2) #即 l=[1, 3, 5, 7, 9]

the method of list

L.append (Var)  #追加元素
L.insert (index,var)
L.pop (Var)   #返回最后一个元素 and removed from list
l.remove (Var)  #删除第一次出现的该元素
L.count (Var)  #该元素在列表中出现的个数
L.index (Var)  #该元素的位置, no throw exception 
L.extend (list) # Append list, that is, merge list to L
l.sort ()    #排序
l.reverse ()   #倒序
list operator:, +,*, Keyword del
a[1:]    # The fragment operator, which is used to extract the child list
[1,2]+[3,4] #为 [1,2,3,4]. Same extend ()
[2]*4    #为 [2,2,2,2]
del l[1]  #删除指定下标的元素
del L[1:3] #删除指定下标范围的元素

copy of List

L1 = L   #L1为L的别名, with C is the pointer address the same, the L1 operation is the L operation. The function argument is this passed
L1 = l[:]  #L1为L的克隆, that is, another copy.

Copy code code as follows: List comprehension
[<expr1> for K in L if <expr2>]

2, Dictionary: Dictionary (that is, C + + standard library map)
Copy code code as follows: Dict = {' Ob1 ': ' Computer ', ' ob2 ': ' Mouse ', ' ob3 ': ' Printer '}
Each element is a pair, containing the key, value two parts. The 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.

the method of dictionary

D.get (key, 0)    #同dict [key], more than the default value is returned, 0. [] There is no throw exception
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
an exception d.clear ()      #清空字典, the same del dict
d.copy ()      #拷贝字典
d.cmp (dict1,dict2) #比较字典, (priority is the number of elements, key size, Key value size)
          #第一个大返回1, small return-1, same return 0

Replication of Dictionary

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

3, tuple: tuple (that is, constant array)
Copy code code as follows: tuple = (' A ', ' B ', ' C ', ' d ', ' e ')
You can extract elements from the [],: operator, of a list. Just can't modify the element directly.

4, String: strings (that is, the list of characters cannot be modified)
Copy code code as follows: str = "Hello My Friend"
A string is a whole. If you want to modify a part of a string directly, it is impossible. But we can read out a part of the string.

Extraction of substring
Copy code code as follows: Str[:6]
String contains a judgment operator: In,not in
"He" in Str
"She" not in Str

String module, which 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, only
#同上反向查找 s.count (Substring,[start [, end]) that produced the valueerror exception was not found
( Substring,[start [, end]]) #返回找到子串的个数
s.lowercase ()
s.capitalize ()   #首字母大写
s.lower ()      #转小写
S.upper ()      #转大写
s.swapcase ()    #大小写互换
s.split (str, ')  #将string转list, with a space to slice
s.join ( List, ')  #将list转string, connecting with spaces

Built-in functions to handle strings

Len (str)        #串长度
cmp ("My Friend", str)  #字符串比较. The first large, return 1
max (' abcxyz ')      #寻找字符串中最大的字符
min (' abcxyz ')      #寻找字符串中最小的字符

Conversion of String

Oat (str) #变成浮点数, float ("1e-1") results in 0.1
int (str)    #变成整型, int ("12") results in
Int (str,base)  #变成base进制整型数 , the result of Int ("11", 2) is 2
long (str)    #变成长整型,
Long (str,base) #变成base进制长整型,

The format of the string (note its escape characters, mostly like the C language, slightly)

Str_format% (parameter list)  #参数列表是以tuple的形式定义的, that is, not running change
Copy code code as follows: >>>print ""%s ' s "%dcm"% ("my brother", 180)
#结果显示为 My brother ' s height is 180cm

The transformation between list and tuple

Tuple (LS) 
list (LS)

Add:

In Python, the list is also an object, so he also has methods and properties that use Help (list) in the Ptython interpreter to view its documents, and some of the open methods are as follows:

The specific use of these methods is described in an instance code here:

# coding=utf-8 # Filename:list.py # date:2012 11 20 # Create a list way heatlist = [' Wade ', ' James ', ' Bosh ', ' Haslem '] tablelist  = List (' 123 ') #list方法接受一个iterable的参数 print ' Miami heat has ', Len (heatlist), ' NBA stars, they are: ' #遍历list中的元素 for player In Heatlist:print player, #向list添加元素 heatlist.append (' Allen ') #方式一: Add parameters to the end of the list object print ' \nafter Allen join the Te AM, they are: ' Print heatlist Heatlist.insert (4, ' Lewis ') #方式二: Insert an element parameter one: Index position parameter two: Object print ' after Lewis join the T EAM, they are: ' Print heatlist heatlist.extend (tablelist) #方式三: Extended list, Parameters: iterable parameters print ' after extend a table list,now the Y are: ' Print heatlist #从list删除元素 heatlist.remove (' 1 ') #删除方式一: The Parameter object, if there is a duplicate element, will only delete the top print "Remove ' 1". Now ' 1 ' is gone\n ', Heatlist heatlist.pop () #删除方式二: Pop optional parameter index deletes the element of the specified location by default to the last element print "Pop", "3 ' \ \", Hea Tlist del heatlist[6] #删除方式三: You can delete the formulation element or the list slice print "Del ' 3 ' at the index 6\n", heatlist #逻辑判断 #统计方法 count parameter: The value of the concrete element print ' J Ames Apears ', Heatlist.count (' Wade '),' Times ' #in and not in print ' Wade in list? ', (' Wade ' in heatlist) print ' Wade is not in list? ', (' Wade ' not in Heatlist) #定位 Index method: Parameter: Value of the specific element optional parameter: Slice range print ' Allen in ' 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 is reversed: ' Heatlist.reverse () print heatlist print ' when The list is sorted: ' Heatlist.sort () #sort有三个默认参数 cmp=none,key=none,reverse=false so you can set the sorting parameters and then talk about the slices of print heatlist #list elements in [start:end] fragments that do not contain end positions print ' elements from 2nd to 3rd ', Heatlist[1:3]

I hope this article will help you with Python programming.

A method for Python to find the difference set, intersection, and set of two lists this article mainly introduces Python to find two list of the difference set, intersection and set of methods, is the Python collection array operation of the common skills, the need for friends can refer to the

In this paper, we describe the method for Python to find the difference set, intersection and set of two list. Share to everyone for your reference. Specifically as follows:

List refers to the difference set between two arrays, the intersection, and set, this elementary school mathematics, the things learned, the following is an example of this analysis.

I. Two list difference sets

If you have the following two arrays:
A = [1,2,3]
b = [2,3]
The desired result is [1]
Here's a record of three implementations:
1. The normal way

Copy code code as follows: RET = []
For I in A:
If I not in B:
Ret.append (i)
2. Condensed version

Copy code code as follows: ret = [I for i in a if I am not in B]
3. Another edition

Copy code code as follows: RET = list (set (a) ^ set (b))
Individuals prefer a third way to implement

Two. Get the collection of two list

Copy code code as follows: Print List (set (a). Union (set (b))
Three. Get the difference set of two list

Copy code code as follows:

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.