Lists, dictionaries, tuples, files--python__python

Source: Internet
Author: User
Tags delete key extend python list
lists (list):

Lists are the most flexible, ordered collection object types in Python.

Unlike strings, lists can contain objects of any kind, and lists are mutable objects that support modifying operations in situ, and can be implemented by means of specified offset values and fragments, list method calls, DELETE statements, and so on. the main properties of the Python list:

An ordered set of arbitrary objects--the list is where other objects are collected, and every item contained in the order is left to right.

Offset read-The Queue Table object is indexed by offset

Variable-length, heterogeneous, arbitrary nesting-lists can grow and shorten in real time, can contain any type of object, support arbitrary nesting

belong to variable sequence classification--support in situ modification

Object reference Array--within the Python interpreter, the list is like an array in C rather than a link structure.


common list constants and actions:

For more comprehensive information, check the Python library manual, or run Help (list), dir (list) to see a complete list of lists methods.

L = [] #一个空列表

L = [0,1,2,3] #四项: index 0 to 3

L = [' abc ', [' def ', ' Ghi ']] #嵌套的子列表

L = list (' spam ') #可迭代项目的列表

L = List (range ( -4,4)) #连续整数的列表, return value: [-4,-3,-2,-1, 0, 1, 2, 3]

L[i] #索引

L[I][J] #索引的索引

L[I:J] #分片

Len (L) #求长度

L1+l2 #合并

L*3 #重复

For x in L:print (x) #迭代

3 in L #成员关系

L.append (4) #增长

L.extend ([5,6,7])

L.insert (i,x) #插入

L.index (1)

L.count (x)

L.sort () #索引

L.reverse () #反转

Del L[k] #方法: Shortening statements

Del L[k:j]

L.pop ()

L.remove (2)

L[K:J] = []

L[k] = 1 #索引赋值

L[K:J] = [4,5,6] #分片赋值

L = [x**2 for x in range (5)] #列表解析

List (Map (ord, ' spam '))


list in the actual application:

Because the list is a sequence, many operations with the same string are supported. Basic list operations:

>>> Len ([1,2,3])
3
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> [1,2,3]*2
[1, 2, 3, 1, 2, 3]

You cannot bring a list and a string together unless you first convert the string to a list or convert the list to a string:

>>> STR ([1,2]) + "
1, 2]34 '
>>> [1,2]+list (" ")
[1, 2, ' 3 ', ' 4 ']

list iterations and parsing:

>>> 3 in [1, 2, ' 3 ', ' 4 ']
False
>>> to X in [1, 2, ' 3 ', ' 4 ']:
...     Print x ... 
1
2
3
4

List Resolution--Builds a new list by applying an expression to each item in the sequence:

>>> res = [c*4 for C in ' spam ']
>>> res
[' ssss ', ' pppp ', ' aaaa ', ' mmmm ']
Manual build of equivalent effects:
>>> res = []
>>> for C in ' spam ':
...     Res.append (c*4) ... 
>>> res
[' ssss ', ' pppp ', ' aaaa ', ' mmmm ']

map--built-in function map applies a function to the items in the sequence and collects the results into a new list

>>> list (map (abs,[-1,-2,0,1,2]))
[1, 2, 0, 1, 2]

index, fragment, matrix

Because lists are sequences, for a list, indexes and fragmentation operations are basically similar to strings--the result of indexing a list is the object at the specified offset, and the list is fragmented to return a new list.


>>> L = [' I ', ' love ', ' Pyton ']
>>> l[2]
' Pyton '
>>> l[-2]
' Love '
> >> l[1:]
[' Love ', ' Pyton ']

matrix (Multidimensional array):A list of nested child lists in Python

Because lists allow nesting, it is sometimes necessary to use multiple indexing operations together. The following example: Using an index operation to get a nested child list, use two indexes to get the specific items in the child list.

>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix[1]
[4, 5, 6]
>>> matrix[1][ 1]
5
>>> matrix[2][0]

Modify the list in situ:

Because the list is mutable, it supports operations that modify the list in situ, rather than forcing a new copy like a string.

index, fragment, assignment:

>>> L = [' I ', ' love ', ' Pyton ']
>>> l[1] = "Love"
>>> L
[' I ', ' love ', ' Pyton ']< c19/>>>> L[0:2] = [' Bob ', ' like ']
>>> L
[' Bob ', ' like ', ' Pyton ']

Note: Both the index and the fragment are modified in situ to modify the list directly, instead of generating a new list as the result

>>> L = [1,2,3]
>>> l[2] = [4,5]
>>> L
[1, 2, [4, 5]]
>>> l[1:2] = [4, 5]
>>> L
[1, 4, 5, [4, 5]]

Piecewise assignment can be understood as two steps (but this is not the case):

1) Delete: Delete the specified fragment to the left of the equal sign

2 Insert: Inserts a fragment from the right side of the equal sign into the location where the old fragment was deleted

This will help you understand why the inserted element does not need to be equal to the number of elements deleted
List method call:

<pre code_snippet_id= "384110" snippet_file_name= "blog_20140609_11_4711602" name= "code" class= "Python" style= " margin-top:4px; margin-right:0px; margin-bottom:4px; margin-left:0px; BACKGROUND-COLOR:RGB (240, 240, 240); ">>>> L = [' I ', ' love ', ' Python ']
>>> l.append (' more ')  #将一个单项加至列表末端, append only allowed to pass in a single object ; L.append (X) and l+[x] results </span>
                       But the former will modify L in situ, which will produce a new list </span>
>>> L
[' I ', ' love ', ' Python ', ' more ']
>>> l.sort ()           #sort原地对列表进行排序, sorted in ascending order
> >> L
[' I ', ' Python ', ' love ', ' more ']   

We can modify the sort behavior by passing in the keyword parameter:

>>> l = [' abc ', ' ABD ', ' Abe ']
>>> l.sort ()
>>> L
[' ABD ', ' Abe ', ' abc ']
>>> L.sort (key=str.lower)
>>> l
[' abc ', ' ABD ', ' aBe ']
>>> L = [' abc ', ' ABD ', ' Abe ']
>>> l.sort (key=str.lower,reverse=true)
>>> L
[' Abe ', ' ABD ', ' abc ']</ Span>

Other method calls:

Sorted

>>> Sorted (l,key=str.lower,reverse=true)
[' aBe ', ' ABD ', ' abc ']
>>> sorted ([X.lower () for X In l],reverse=true)  #使用列表解析在排序之前转换为小写
[' Abe ', ' Abd ', ' ABC ']

Extend ()--Inserts multiple elements at the end of the list.

Pop ()--Deletes an element. Reversed ()-in-situ flipping lists must be included in a list call because it is an iterator.

<span style= "font-family:arial, Helvetica, Sans-serif;" ><span style= "White-space:normal;" ><span style= "Font-family:monospace;" ><span style= "WHITE-SPACE:PRE;" ></span></span></span></span><p style= "MARGIN-TOP:4PX; margin-right:0px; margin-bottom:4px; margin-left:0px; padding-top:2px; padding-right:0px; padding-bottom:2px; padding-left:0px; "><span style=" font-family:monospace; ><span style= "WHITE-SPACE:PRE; "></span></span></p><span style=" font-family:monospace; ></span><pre name= "code" class= "Python" style= "MARGIN-TOP:4PX; margin-right:0px; margin-bottom:4px; margin-left:0px; BACKGROUND-COLOR:RGB (240, 240, 240); ">>>> L = [1,2] >>> l.extend ([4,5,6]) >>> L [1, 2, 4, 5, 6] >>> L.pop () 6 >>& Gt l [1, 2, 4, 5] >>> l.reverse () >>> L [5, 4, 2, 1] >>> list (reversed (L)) [1, 2, 4, 5] 



>>> L = []
>>> L.append (1)
>>> L.append (2)
>>> L
[1, 2]
>>> L.pop () #pop () method defaults to last element
2
>>> L = [' I ', ' love ', ' Pyton ']
>>> l.index (' Love ')
1
>>> L.insert (1, ' love ')
>>> L
[' I ', ' Love ', ' love ', ' Pyton ']
>>> l.remove (' Love ')
>>> L
[' I ', ' love ', ' Pyton ']
>>> L.pop (1) #pop () method can also specify the offset that will delete and return elements
' Love '
>>> L
[' I ', ' Pyton ']

Other common list actions:

The del--list is mutable, and you can use the DEL statement to delete an item or a fragment in situ

>>> L = [' I ', ' love ', ' Pyton ']
>>> del l[0]
>>> l
[' Love ', ' Pyton ']
>> > del l[1:]
>>> L
[' Love ']


Because a slice assignment is a delete plus insert operation, you can delete a list fragment by assigning an empty list to a fragment

>>> L = [' I ', ' love ', ' Pyton ']
>>> l[1:] = []
>>> L
[' i ']
>>> l[0] = []
>>> L
[[]]



Dictionary (dictionary):

In addition to the list, the dictionary may be the most flexible built-in data structure type in Python. If you think of a list as an ordered collection of objects, you can use the dictionary as a collection of unordered objects, the main difference being that the elements in the dictionary are accessed by keys, not by offsets. The main attributes of the Python dictionary:

Read by key rather than by offset--the dictionary is sometimes called an associative array or a hash table, linked by a key to a series of values.

Unordered collection of arbitrary objects--items in a dictionary have no specific order.

Variable-length, heterogeneous, arbitrary nesting-dictionaries can grow and shorten in situ (without generating a copy), can contain any type of object, and support arbitrary depth nesting.

belong to a variable mapping type--the dictionary can be modified in situ by assigning values to the index.

Object reference Table--The dictionary supports the Unordered object reference table read by the key, and the list supports an array of object references that the location reads. Common Dictionary constants and actions:

This example summarizes some representative dictionary operations (view library manuals or run dir (dict)--{use dir to get a list of available variable names within the module} or Help (Dict) to get a complete list of the type named Dict). When written as a constant expression, the dictionary appears in a series of "Key: Value (Key:value)" forms, separated by commas, enclosed in braces. An empty dictionary is a pair of curly braces, and a dictionary can be nested as a value in another dictionary (list, tuple).

>>> D = {} #空字典

>>> D = {' spam ': 2, ' Eggs ': 3} #两项目字典

>>> D = {' food ': {' Ham ': 1, ' Eggs ': 2}}} #嵌套

>>> D = Dict.fromkeys ([' A ', ' B ']) #其他构造技术

>>> D = dict (Zip (keylist,valslist)) #关键字, corresponding pairs, List of keys

>>> D = dict (name= ' Bob ', age=42)

>>> d[' eggs '] #以键进行索引运算

>>> d[' food ' [' Ham ']

>>> ' eggs ' in D #键存在测试

>>>d.keys #方法: Key

>>>d.values# Method: Value

>>>d.items #方法: Key + value >>>d.copy# method: Copy

>>>d.get (key,values) #方法: Default

>>>d.update (D2) #合并

>>>d.pop (Key) #删除等

>>>len (D) #长度

>>>d[key] = #新增/modifier key, delete key

>>>deld[key] #根据键删除条目

>>>list (D.keys ()) #字典视图 (Python 3.0)

>>>d1.keys () & D2.keys () >>>dictionary Views (Python 3.0)

>>>d = {x:x*2 for x in range (a)} #字典解析 (Python 3.0)

the dictionary in Practical application:

Dictionaries are indexed by keys, nested dictionaries are represented by a series of indexes, and when Python creates a dictionary, it stores items in the order that they are selected, left to right, and provides keys for values. basic operation of the dictionary:

>>> d = {' spam ': 2, ' Ham ': 1, ' Eggs ': 3}
>>> d[' spam ']
2
>>> D
{' Eggs ': 3, ' Ham ': 1, ' spam ': 2}

Note: The final output in this example is different from the order originally set. The purpose of this design is to quickly perform a key lookup (that is, hash lookup), keys need to be randomly set in memory here is why it is assumed that right-to-left order (for example, fragmentation and merging) is not suitable for dictionaries, and only keys are used in dictionaries, not values.

>>> Len (d)                   #返回keys列表长度或字典中元素数目
3
>>> ' Ham ' in D               #测试键是否存在
True
>> > List (D.keys ())           #建立关于key的列表
[' eggs ', ' ham ', ' spam ']


In Situ modified dictionary:

Dictionaries are mutable so they can be modified, extended, and shortened without the need to generate a new dictionary.

A simple assignment can generate or alter an element.

>>> D
{' Eggs ': 3, ' Ham ': 1, ' spam ': 2}
>>> d[' ham '] = [' I ', ' am ', ' WY ']          #改变键值对应的valus
& Gt;>> D
{' Eggs ': 3, ' Ham ': [' I ', ' am ', ' WY '], ' spam ': 2}
>>> del d[' eggs ']                 #通过键值删除values
>>> D
{' Ham ': [' I ', ' am ', ' WY '], ' spam ': 2}
>>> d[' new ' = ' apple '            #增加新的values for Apple,key For ' new '
>>> D
{' new ': ' Apple ', ' ham ': [' I ', ' am ', ' WY '], ' spam ': 2}

Note: Python in the list treats the offset beyond the end of the list as a border and complains, so you need to use the Append method or the fragment assignment in the list, but you can assign a new dictionary key in the dictionary without having to consider the problem.


Other dictionary methods:

Eg:

The values of the dictionary and the items method return the dictionary's Value List and (key,values) to the tuple, respectively.

>>> D = {' spam ': 2, ' Ham ': 1, ' Eggs ': 3}
>>> list (d.values ())
[3, 1, 2]
>>> list (D.items ())
[(' Eggs ', 3), (' Ham ', 1), (' Spam ', 2)]

The above method is very effective in iterating through the dictionary items in a loop. There is an error in reading a nonexistent key, and the default value (none or user-defined default value) is returned by a GET method when the key does not exist. This is a way to fill in the default value to avoid Missing-key errors when the key does not exist:

>>> d.get (' spam ')
2
>>> print d.get (' new ')
None
>>> d.get (' new ', 12)
12

The dictionary Update method is somewhat similar to merging, but it has nothing to do with Left-to-right order (again, there is no such thing in the dictionary).

>>> D = {' spam ': 2, ' Ham ': 1, ' Eggs ': 3}
>>> D2 = {' new ': 4, ' name ': 6}
>>> d.update (D2)
>>> D
{' New ': 4, ' eggs ': 3, ' Ham ': 1, ' name ': 6, ' spam ': 2}

When you merge the key values of a dictionary into another dictionary, there is a case where the key value is overwritten:

>>> D = {' spam ': 2, ' Ham ': 1, ' Eggs ': 3}
>>> D2 = {' new ': 4, ' Eggs ': 6}
>>> d.update (D2)
>>> D
{' New ': 4, ' eggs ': 6, ' Ham ': 1, ' spam ': 2}

A dictionary pop method can remove a key from the dictionary and return his value (the difference from the pop method of the list is to delete the key instead of an optional location):

>>> d = {' new ': 4, ' eggs ': 3, ' Ham ': 1, ' name ': 6, ' spam ': 2}
>>> D
{' new ': 4, ' eggs ': 3, ' spam ' : 2, ' Ham ': 1, ' Name ': 6}
>>> D.pop (' new ')
4
>>> D
{' Eggs ': 3, ' spam ': 2, ' Ham ': 1, ' Nam E ': 6}
>>> L = [' AA ', ' BB ', ' cc ', ' DD ']
>>> 
>>> l.pop ()
' DD '
>> > L.pop (1)
' BB '
>>> L
[' AA ', ' CC ']


META Group:

Tuples-a collection of objects that cannot be modified.

Tuples are composed of simple objects, similar to lists, except that tuples cannot be modified in situ (they are immutable) and are usually written in parentheses in a series of

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.