Quick start of basic operations for list (list), tuple (tuple), Dict (dictionary) in Python

Source: Internet
Author: User
Tags shallow copy python list


Recently looked at Python's list, dictionaries and tuples and other data types, feel that these data types are more commonly used, by the way, summed up some of the more common usage.

    1. The list is the most commonly used data type in Python, and the list can be changed, and the use is very simple, the following:

1) If you create a list:

List1 = [1,2,3]list2 = [' A ', ' B ', ' c ']list3 = [, ' A ', ' B ', ' abc ']LIST4 = [1,[2,3],[' A ', ' B ', ' c]] #创建一个有序列表list5 = range ( #创建一个二维列表list6 = [[0 for Col in Range] ' for row in range (10)]

2) Access the values in the list

#!/usr/bin/env python# -*-coding:utf-8 -*-list1 = [1,2,3,4,5,6] #如取出list1列表中第二个元素的值: ( Note: The subscript of the list is starting from 0) print (the value of the second element of the ' List1 list is:%d '  % list1[1])   #如果想取出其它元素以此类推 # The value of the element in the output list print (' Traverse the output list1 values of all elements: ') for i in list1:    print (i) #输出列表中奇数项的值 (i.e., 1th, 3, 5 in the Remove list ...). The value of the odd item in print (' Output list1: ') for j in list1[::2]:  #这里使用了列表的切片以及步长      Print (j) list2 = [1,2,[3,4,[6,7,8]]] #取出列表list2中的值3的元素print (' Take out the element of value 3 in list list2%s: '  % list2 ') Print (list2[2][0]) "principle: First Look at the value of 3 in a sub-list, and this sub-list belongs to the outer list (parent list) of the third element, first take out the sub-list containing the value 3 is: list2[2], because list2[2] is still a list, The value 3 is in the position of the first element of the list, so we can still remove the first element of the list2[2] sub-list by the list (List2[2][0], that is, the element with the value 3 is removed. ' #取出列表list2中的值8的元素print (' Remove the element in list list2%s of value 8: '  % list2 ') print (list2[2][2][2])   #参照上边以此类推 ' " The result is as follows: The value of the second item of the List1 list is: 2 traverses the value of the output List1 all elements: 123456 The value of the odd item element in the output List1:135 Remove list list2[1, 2, [3, 4, [6, Elements of value 3 in  7, 8]]]: 3 Remove list LIST2[1, 2, [3, 4,&NBsp [6, 7, 8]] element in value 8:8 "'

3) Add or modify the value of the list

#!/usr/bin/env python#-*-coding:utf-8-*-list3 = [' Python ', ' Java ', ' Php ']print (' original list list3:%s '% list3) # Add an element to List3 List3.append (' C # ') Print (' Add an element to List3 c#:%s '% list3) #修改列表list3的第一个值为Python3list3 [0] = ' Python3 ' Print (' The first element of the modified list list3 the value of python3:%s '% list3) ' and the result is as follows: The original list list3: [' python ', ' Java ', ' Php '] add an element to the List3 ' Python ', ' Java '. , ' php ', ' C # '] Modify list list3 The value of the first element is python3:[' Python3 ', ' Java ', ' php ', ' C # ' "


4) Remove elements from the list

#!/usr/bin/env python#-*-coding:utf-8-*-list4 = [' Python ', ' Java ', ' Php ', ' Go ']print (' original list:%s '% list4) #删除值为Php的元素del List4[2]print (' Remove elements of php:%s '% list4) #删除值为Go的元素list4. Pop () print (' delete element of Go ':%s '% list4) ' ' Runs the result as follows: [' Python ', ' Java ', ' php ', ' go '] remove the value of the PHP element: [' python ', ' Java ', ' go '] Delete the value of the Go element: [' python ', ' Java '] '

5) Some other basic operations of the list

#!/usr/bin/env python#-*- coding:utf-8 -*-list1 = [1,2,3,4,5]list2 = [' Python ', ' Java ', ' Php ', ' Go ']print (' list list1:%s '  % list1) print (' list list2:%s '  % list2) # Gets the length of the list List1 L = len (list1) print (' list list1 of length:%d '  % l) #合并list1和list2成为一个新的列表list3list3  = list1 + list2print (' Merge List1 and List2 become a new list:%s '  % list3) # Creates a list of the specified length with the same element value list4list4 = [' Python '] * 4print (' Create a list of the specified length with the same element value:%s '  % list4 ) #判断元素3是否存在于列表list1中f  = 3 in list1print (' Determine if element 3 exists in List List1:%s '  % f) # Intercept the value after the second element in the list list2 list5 = list2[1:]print (' list element after the second element in the Intercept list List2:%s '  % list5) # Gets the maximum value of the element in the list List1 Max_value = max (list1) print (the maximum value of the element in the list List1 is:%d '  % max_value) # Gets the minimum value of the element in the list List1 min_value = min (list1) print (the minimum value for the element in the list List1 is:%d '  % min_value) #将元组转化成列表a  =  (a) list6 = list (a) print (' Tuple (all in a) ' converted to a list of:%s '  %  list6) #将字符串转化成列表s  =  ' abc ' list7 = list (s) print ("String ' abc ' converted to a list of:%s"  % list7) # The list is converted to a string:list8 =  "". Join (LIST7) print ("list [' A ', ' B ', ' C ') converts the string to:%s"  % list8) #应用场景如: Do a concatenation of the addition operation # expr =  "+". Join ([]) #结果为: 1+2+3 ' Run the result as follows: The list list1: [1, 2, 3, 4,  5] List list2: [' Python ',  ' Java ',  ' Php ',  ' Go '] The length of the list List1 is: 5 merge List1 and list2 into a new list: [1, 2,  3, 4, 5,  ' python ',  ' Java ',  ' Php ',  ' Go ' creates a list of the same length with the same element value: [' Python ',  ' Python ',  ' python ',  ' python ' to determine whether element 3 exists in the list List1: true to intercept list elements after the second element in the List2 list: [' Java ',  ' Php ',  The maximum value of the elements in the ' Go ' list List1 is: 5 The minimum value of the elements in the list List1 is: 1 tuples (All-in-a-box) into the list: [1, 2, 3] The string ' abc ' is converted to a list of: [' A ',  ' B ',   ' C '] list [' A ', ' B ', ' C '] into the string: ABC '

6) Examples of methods included in the Python list

#!/usr/bin/env python#-*- coding:utf-8 -*-#注意以下的列表操作都是对原列表进行操作list  = [3,2,4,1,5]print (' The original list is:%s '  % list) #在列表尾部添加新元素list. Append (6) Print (' Add a new element at the end of the list 6:%s '  % list) # Inserts a new element in the list 2nd position 3list.insert (1,3)       #注意列表的下标是从0开始print (' Inserts a new element in the 2nd position of the list 3:% S '  % list) print (' Append the value of another list '%s ' at the end of the list:%s ') #在列表尾部追加另一个列表的值list1  = [1,2,3]list.extend (List1)  %  (list1,list)) #统计列表list中值为3的元素出现的次数count  = list.count (3) print (' number of elements with a value of 3 in the list of statistics:%d '  % count) #找出列表list中第一个值3的元素的索引index  = list.index (3) Print (' Index of the element that finds the first value 3 in list:%d '  %  index) #移除列表中第2个元素  #### #注意: By default List.pop () is the last element in the removal list list.pop (1)              #注意list下标是从0开始print (' Remove 4th element in list:%s '  % list) # Removes the first element in the list with a value of 3 List.remove (3) print (' Remove the first element in the list with a value of 3:%s '  % list) #对list列表进行排序list. Sort ()  # By default, print is sorted by asscii (' sort list lists:%s '  % list) #反转列表中的元Vegetarian List.reverse () print (' Reverse the element in list:%s '  % list) #反转列表中的元素list. Reverse () print (' Inverted list:%s '  % list The run results are as follows: The original list is: [3, 2, 4, 1, 5] Adds a new element at the end of the list 6:[3, 2, 4, 1, 5,  6] Insert a new element in the 2nd position of the list 3:[3, 3, 2, 4, 1, 5, 6] Append the value of another list [1, 2, 3] at the end of the list: [ 3, 3, 2, 4, 1, 5, 6, 1, 2, 3] Statistics list the number of elements with a value of 3 appears: 3 finds the index of the element that is the first value 3 in the list: 0 removes the 4th element in the list: [3, 2, 4, 1, 5, 6, 1,  2, 3] Removes the first element in the list with a value of 3: [2, 4, 1, 5, 6, 1, 2, 3] Sorts the list: [1,  1, 2, 2, 3, 4, 5, 6] Reverses the elements in the list: [6, 5, 4, 3, 2, 2,  1, 1] ""

7) Comparison of the shades of the list and its rationale

#!/usr/bin/env python#-*- coding:utf-8 -*-#list列表浅拷贝示例import   copylist1 = [ 1,2,3,[4,5,6]]list2 = list1.copy () print (the value of ' List1:%s '  % list1) print (' List2 value:%s '  %  LIST2) "The value of the run result to List1 is: [1, 2, 3, [4, 5, 6]]list2 value is: [1, 2, 3, [4 ,  5, 6]] "#修改list2中的值list2 [The value of 0] = 3print (' List1:%s '  % list1) print (' List2 ' value is:%s '  % list2 ' runs the result: the value of List1 is: [1, 2, 3, [4, 5, 6]]list2 value: [3, 2, 3 ,  [4, 5, 6]] "We will list1 copy one copy to List2, when the first element of the change List2 value is 3, the value of List1 has not changed, this is very good understanding, then please continue to see" ' # Continue to modify the value of List2, this time modify the value of the List2 sub-list list2[3][0] = 5print (' List1 value:%s '  % list1) print (' List2 value:%s ')  % LIST2) The value of "List1" is: [1, 2, 3, [5, 5, 6]]list2 value is:[3, 2, 3,  [5, 5, 6]]   With this modification, we will be surprised to find that this time we have modified the first element of the List2 sub-list to 5, why is the value of the first element in the List1 's sub-list also changed?   Reason: Shallow copy only copy (copy) The first layer of the list, also take the above as an example, for the first time when modifying the first element of List2, because the first element of the list List1 is a real value, the list2 copies the value directly at the time of the copy, so List2 will not affect the value of list1 when modifying this value. While list2 the second time, the change is the value in the sub-list, and the fourth position in List1 is not the value of the sub-list, but a reference address of the sub-list, because the shallow copy only copy (copy) a layer, so the list2 in the copy, is to copy the reference address of the List1 neutron list, when the fourth element in List1 and List2 holds the same reference address, pointing to the same sub-list, so when you modify the value of a sub-list in either List1 or List2, The value of the other list's sub-list also changes.   Note several ways to:  shallow copy  p1 = copy.copy (List1)  p2 = list1[:]  p3 =  list (List1)   above these kinds of methods are shallow copies, the use of the time need to pay attention to, or there will be pits ... "Deep copy is implemented as follows: List4 = copy.deepcopy (list1) deep copy is actually completely copy the list once, modify any one, will not affect the other list"

2. Tuples (tuple) are similar to lists, with the biggest difference being that the elements of a tuple cannot be modified

1) Create a tuple

#创建一个空的元组tup1 = () #创建只包含一个元素的元组tup2 = (' A ',) #注意需要在元素后边添加逗号 # Create a tuple with multiple elements Tup3 = ("Java", ' Python ', ' Php ')

2) basic operation of tuples

#!/usr/bin/env python#-*- coding:utf-8 -*-tup1 =  (tup2 = ) (' Python ', ' Java ', ' Php ', ' C # ') #访问元组tup2中的第一个元素s  = tup2[0]print (' access the first element in the tuple tup2:%s '  % s) # Traverse all elements in the output tuple tup2: print (' Traverse all elements in the output tuple tup2: ') for i in tup2:    print (i) # Merging Tup1 and Tup2 as a new tuple (that is, connecting two tuples) tup3 = tup1 + tup2    #注意: There is no modification to the tuple, Instead, the two tuples were merged into a new tuple, and the old tuples were not modified. Print (The new tuple for merge tup1 and tup2: '  , tup3) #删除元组   elements within a tuple are not allowed to be deleted because they cannot be modified, but we can use Del to delete an entire tuple del  tup3# If you delete an entire tuple, you cannot access the tuple, otherwise the not defined exception error # is calculated for the length of the tuple tup2: L = len (tup2) print (' The length of the calculated tuple tup2 is:%d '  % L) #判断元素3在元组tup1是否存在: B = 3 in tup1print (' Determine if element 3 exists in tuple Tup1:%s '  % b) # Remove maximum value in tuple tup1: Max = max (tup1) print (maximum value in tuple tup1:%d '  % max) #取出元组tup1中的最小值:min =  Min (tup1) print (' minimum value in tuple tup1:%d '  % min) #将列表转换为元组list1  = [' A ', ' B ', ' C ']tup4 = tuple (list1) Print (' listlist1%s converted to tuples:%s '  %  (LIST1, TUP4)) #以上为列表的一些基本操作, the primary tuple is not modifiable, for example: tup1[1] = 10 such operations are illegal. The results of the operation are as follows: accesses the first element in the tuple tup2: Python iterates through all the elements in the output tuple tup2: pythonjavaphpc# merges Tup1 and tup2 with the new tuple:  (1, 2, 3,   ' Python ',  ' Java ',  ' Php ',  ' C # ') The length of the calculated tuple tup2 is: 4 Determines whether element 3 exists in tuple Tup1: True tuple tup1 Maximum value: 3 tuple tup1 Minimum value: 1 list list1[' A ',  ' B ',  ' C '] converted to tuple: (' a ',  ' B ',  ' C ') '

The 3.Python Dictionary (dict) uses Key-value storage similar to the map in other languages, with a format of D = {key1:value1, key2:value2}, and can store any type of object, but the key of the dictionary is an immutable type. and value can be changed, and only allowed

The same key appears once (if the same key is assigned two times, the previous value is overwritten the next time).

1) The general definition of the dictionary is as follows: (note the format of the dictionary dict)

D1 = {' A ': 1, ' B ': 2, ' C ': 3}d2 = {' Beijing ': [' changping ', ' Chaoyang ', ' daxing ', ' Dongcheng '], ' Shanghai ': [' Hongkou ', ' jiading ', ' Pudong ', ' Songjiang ']}

2) accessing values in the dictionary

#!/usr/bin/env python#-*-Coding:utf-8-*-d1 = {' name ': ' Zhangsan ', ' age ': +, ' addr ': ' beijing '} #输出字典d1中age的值a = d1[' age ' ] #或者 a2 = d1.get (' Age ') print (' The value of age in the output dictionary D1:%d '% a) #便利输出字典中的key和valueprint (' traverse the output in the form of a dictionary into a list: ') print (' D1.items () The result is: ', D1.items ()) #items () converts the key/value inside the dictionary into a tuple, converting the entire dictionary into a list containing tuples for key,value in D1.items (): Print (key,value) print (' Directly traverse the value in the output Dictionary: ') for I in D1:print (I,d1[i]) "" The result is as follows: Output dictionary D1 The value of age: 21 the dictionary is converted to a list to traverse the output: The result of D1.items () is: Dict_items ([(' Name ', ' Zhangsan '), (' age ', +), (' addr ', ' Beijing ')]) name Zhangsanage 21addr Beijing directly traverse the values in the output dictionary: name Zhangsanage 21addr Beijing ""

3) Some other basic operations of the dictionary, such as modifying, adding, deleting

#!/usr/bin/env python#-*- coding:utf-8 -*-d1 = {' name ': ' Zhangsan ', ' age ': +, ' addr ': ' Beijing '} #为字典添加一个新的键值对 ' gender ': ' Male ': d1[' gender '] =  ' Male ' Print ("Add a new key value to the dictionary ' gender ': ' Male ' after:", D1) #修改d1中age的值为22: d1[' age '] = 22print (' modify the value of age in D1: ', D1) #删除d1中的addrdel  d1[' addr ']print (' Delete addr in D1: ', D1) ' D1.clear ()   #能够清空字典del  d1   #是删除字典 ' #将两个列表合成一个字典list1  = [' a ', ' B ', ' C ', ' d ']list2 = [1,2,3,4]d2 = dict (Zip (list1,list2)) print (' combine two lists of a dictionary: ', D2) ' The results are as follows: Add a new key value to the dictionary ' gender ': ' Male ':  {' name ':  ' Zhangsan ',  ' age ': 21,  ' addr ':  ' Beijing ',  ' gender ':  ' male '} modifies the value of age in D1 ' name ' 22: {':  ' zhangsan ' age ',  ' Addr ':  ' Beijing ',  ' gender ':  ' male '} delete D1 ' name ' addr: {':  ' zhangsan ' age ',  22,  ' gender ':  ' male '} synthesizes two lists of a dictionary:  {' A ': 1,  ' B ': 2,  ' C ': 3,  ' d ':  4} "

4) A simple example of a built-in method of a dictionary:

#!/usr/bin/env python#-*- coding:utf-8 -*-d1 = {' name ': ' Zhangsan ', ' age ': +, ' addr ': ' Beijing '} #获取字典d1的所有键 (key): Keys = d1.keys ()        # Returns the value of all keys as a list print (' Get all Keys for dictionary D1 (key): ',  keys) #获取字典d1的所有值 (value): Values = d1.values ()      #以列表形式返回所有value的值print (' Get all values of the dictionary D1 (values): ',  values) #对字典进行一次浅拷贝d2  = d1.copy ()         #返回字典的一个浅拷贝print (' Original dictionary: ', d1) print (' Copy of Dictionary: ', D2) #取出字典d1中键为addr的值addr  =  D1.get (' addr ')     #返回指定键的值, if it does not exist, you can return to the default value specified print (' Remove the value of the dictionary D1 key to addr:%s '  % addr) # Remove the value of the Dictionary D1 key to gender, add g = d1.setdefault (' Gender ', ' Male ')     #如果字典中不存在该键 if it does not exist, The key and the specified default value will be added to the dictionary print (' Remove the value of the Dictionary D1 key to gender, add: ', D1) #把另一个字典中的键值对跟新到字典d1中: d3 = {' hobby ': ' Meizi '} D1.update (D3)         #把另个字典的键/value update to D1 in print ("Put another dictionary d3{' hobby ': ' Meizi '} Key-value pairs in the dictionary D1: ",  d1) #删除字典中键age所对应的值 and return value to v = d1.pop (' age ')      #删除字典中指定的键以及对应的值, and returns the value of the key print (' delete the value corresponding to the key age in the dictionary and Return ' value ': ',  v) Print (' This time the dictionary D1 contains an entry that has: ',  D1) #随机删除字典d1中的一对键值 and returns the change-key value pair: Kv = d1.popitem ()        #随机删除字典中的一对键值并将结果返回print (' randomly delete a pair of key values in the dictionary D1 and return the key value pair: ',  kv) print (' This time the dictionary D1 contains: ',  D1) # Delete all elements within the dictionary D1 D1.clear () print (' Delete all elements within dictionary D1: ',  d1) #创建一个新字典d4 ={}.fromkeys ((' A ', ' B '), 1)    # Create a new dictionary with the element in SEQ as the key, with Val as the dictionary key corresponding to the initial value of print (' Create a new dictionary D4: ',  d4) ' ' Run the result as follows: Gets all keys for dictionary D1 (key):  dict_keys ([' Name ',  ' age ',  ' addr ') gets all values of the dictionary D1:  dict_values ([' Zhangsan ', 21,  ' Beijing ']) the original dictionary:  {' name ':  ' Zhangsan ',  ' age ': 21,  ' addr ':  ' Beijing '} Copy of dictionary:  {' name ':  ' Zhangsan ',  ' age ': 21,  ' addr ':  ' Beijing '} remove the value of the dictionary D1 in addr: Beijing Remove the value of the dictionary D1 in gender, and add if it does not exist:  {' name ':  ' Zhangsan ',  ' age ': 21,  ' addr ':  ' Beijing ',  ' gender ':  ' male '} Take another dictionary d3{' hobby ': key-value pairs in ' Meizi ' and new to dictionary D1:  {' name ':  ' Zhangsan ',  ' age ': 21,  ' addr ':  ' Beijing ',  ', gender ':  ' male ',   ' hobby ':  ' Meizi '} deletes the value corresponding to the key age in the dictionary and returns the value:  21 this time the dictionary D1 contains the following items:  {' name ':  ' Zhangsan ',  ' Addr ':  ' Beijing ',  ' gender ':  ' male ',  ' hobby ':  ' Meizi '} randomly deletes a pair of key values from the dictionary D1 and returns the change-key value to:  (' Hobby ',  ' Meizi ') at this point the dictionary D1 contains the following items:  {' name ':  ' Zhangsan ',  ' addr ':  ' Beijing ',  ' gender ':   ' Male ' delete all elements within dictionary D1:  {} Create a new dictionary d4: {' a ': 1,  ' B ':  1} '


Quick start of basic operations for list (list), tuple (tuple), Dict (dictionary) in Python

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.