Python list (list), dictionary (dict), Strings (string) Basic Operations Summary _python

Source: Internet
Author: User
Tags extend throw exception python list

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
Copy Code code as follows:

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
Copy Code code as follows:

For element in Sample_list:
print ' element '

Python list advanced Operations/Tips

Produces a list of numeric increments

Copy Code code as follows:

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

Initialize a list with a fixed value
Copy Code code as follows:

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]

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)
A = [' I ', ' You ', ' he ', ' she '] # element can be of any type.

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

Copy Code code as follows:

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

Create a contiguous list
Copy Code code 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]

The method of list
Copy Code code as follows:

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 throw exception
L.extend (list) #追加list, that is, merge list to L
L.sort () #排序
L.reverse () #倒序
List operator:, +,*, key word del
A[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
Copy Code code as follows:

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

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

Copy Code code as follows:

D.get (key, 0) #同dict [key], more than the default value is returned, 0. [] No exception thrown
D.has_key (key) #有该键返回TRUE, or False
D.keys () #返回字典键的列表
D.values () #以列表的形式返回字典中的值, the list of returned values can contain duplicate elements
D.items () #将所有的字典项以列表方式返回, each of these lists is from (key, value), but the item does not have a special order when it returns

D.update (DICT2) #增加合并字典
D.popitem () #得到一个pair, and remove it from the dictionary. Empty throws exception
D.clear () #清空字典, with 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
Copy Code code as follows:

"He" in Str
"She" not in Str

String module, which also provides a number of methods, such as
Copy Code code as follows:

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 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, split by Space
S.join (list, ') #将list转string, connecting with spaces


Built-in functions to handle strings
Copy Code code as follows:

Len (str) #串长度
CMP ("My Friend", str) #字符串比较. First large, return 1
Max (' abcxyz ') #寻找字符串中最大的字符
Min (' abcxyz ') #寻找字符串中最小的字符

Conversion of String
Copy Code code as follows:

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

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

The transformation between list and tuple

Tuple (LS)
List (LS)

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.