The use of a list tuple dictionary for Python data structures

Source: Internet
Author: User

Meaning of data structure

Before we learn the data structure, we first understand the meaning of the data structure. A data structure is a collection of elements that are organized in a way, such as numbering elements, that can be numbers or characters, or even other data structures. In the Python language, the most basic data structure is the sequence (sequence). Each element in the sequence is assigned an ordinal ———— that is the position of the element, called an index or subscript, and the index increments from 0.

A typical sequence consists of a list, a tuple, and a string. Where the list is mutable (modifiable), and tuples and strings are immutable (once created are fixed). Lists, tuples, and strings are also more commonly used data structures.

This article focuses on Python's list, tuples, dictionaries, and the next chapter describes the operation of strings.

list, using the [] definition, the individual elements in [], separated by commas.

Example

    • Defines a list named All_star that contains the KOBE,TMAC,LBJ element
      >>> all_star = ["Kobe","TMAC","LBJ"]>>> print(all_star)[‘Kobe‘, ‘TMAC‘, ‘LBJ‘]
    • Lists can also contain lists, such as:
      >>> east_star = ["Irving","Wall","Love"]>>> west_star = ["Curry","KD","Harden"]>>> all_star = [west_star,east_star]>>> print(all_star)[[‘Curry‘, ‘KD‘, ‘Harden‘], [‘Irving‘, ‘Wall‘, ‘Love‘]]
    • Or
      >>> all_star = [["Kobe","TMAC"],["LBJ","BOSH"]]>>> print(all_star)[[‘Kobe‘, ‘TMAC‘], [‘LBJ‘, ‘BOSH‘]]
      List support additions and deletions change

      All sequence types can perform certain operations, which are determined by the object properties. These operations include: index (indexing), slice (sliceing), add (adding), multiply (multiplying), and check whether some elements belong to a sequence member, calculate the length of a sequence, find the largest, smallest element of the built-in function.

A single index can be used to remove an element at a time, using a slice, you can remove the elements within a specified range, and the shards are implemented by two index values separated by two colons.

  • Example 1, a single index Gets the element, gets the element named Kobe in the All_star list
     >>> All_star = ["Kobe", "TMAC", "LBJ"] #元素的下标也就是索引, starting from 0, incrementing one by one. Kobe elements are labeled 0,tmac as 1,LBJ for 2>>> print (all_star[0]) kobe>>> All_star = [["Kobe", "TMAC"],["LBJ", "BOSH"] ]>>> print (all_star[0][0]) Kobe  
  • Example 2, use of slices
     >>> All_star = [' Curry ', ' KD ', ' harden ', ' Irving ', ' Wall ', ' Love '] #索引范围, the left side contains, the right is not included, when you want to take the first 3 elements, the slice range is 0:3.>>> all_star[0:3] [' Curry ', ' KD ', ' Harden ']  
     Code class= "Language-python" > #从第一个元素, take the last element >>> all_star[1:] [' KD ', ' harden ', ' Irving ', ' Wall ', ' Love ']
          
      #忽略第一个和最后一个元素 >>> all_star[1:-1] [' KD ', ' harden ', ' Irving ', ' Wall ']  
      #从第二个元素开始, one for every other, 2 for step, and the default step to 1.>>> all_star[1:- 1:2] [' KD ', ' Irving ']  
      #在下标为2的位置, right-to-left values until the last value. >>> all_star[2::-1] [' Harden ', ' KD ', ' Curry ']  

    Increment, append (), insert ()

  • Example:
    >>> all_star[‘Curry‘, ‘KD‘, ‘Harden‘, ‘Irving‘, ‘Wall‘, ‘Love‘]#把元素添加到最后>>> all_star.append("LBJ")    >>> all_star[‘Curry‘, ‘KD‘, ‘Harden‘, ‘Irving‘, ‘Wall‘, ‘Love‘, ‘LBJ‘]
    #把元素插入到指定位置>>> all_star.insert(2,"Westbrook")    >>> all_star[‘Curry‘, ‘KD‘, ‘Westbrook‘, ‘Harden‘, ‘Irving‘, ‘Wall‘, ‘Love‘, ‘LBJ‘]

    Change, using the direct substitution method

  • Example:
    >>> all_star[‘Curry‘, ‘KD‘, ‘Westbrook‘, ‘Harden‘, ‘Irving‘, ‘Wall‘, ‘Love‘, ‘LBJ‘]#为需要替换的元素下标赋予新值>>> all_star[6]="George"    >>> all_star[‘Curry‘, ‘KD‘, ‘Westbrook‘, ‘Harden‘, ‘Irving‘, ‘Wall‘, ‘George‘, ‘LBJ‘]

    Delete, remove (), Pop (), Del

  • Example:
      #remove () method to directly delete content >>> All_star.remove ("LBJ") >>> All_ star[' Curry ', ' KD ', ' Westbrook ', ' harden ', ' Irving ', ' Wall ', ' George ']  
      #pop () method deletes content based on index value and returns the deleted value >>> all_star.pop (6) ' George ' >>> All_star [' Curry ', ' KD ', ' Westbrook ', ' harden ', ' Irving ', ' Wall ']  
      #del命令根据索引值删除内容, no return >>> del all_star[5] >>> All_star [' Curry ', ' KD ', ' Westbrook ', ' harden ', ' Irving ']  
      #del命令删除列表对象 >>> del All_star >>> All_star Traceback (most recent call last): File "<stdin>", line 1, in <module>nameerror:name ' All_star ' are not defined  pre> 

    Some built-in functions:

  • Count () Number of occurrences of the statistic element
    >>> list1 = [1,2,3,4,5,4,3,2,1,1,0,1]>>> list1.count(1)4
  • Extend () appends multiple values from another sequence at the end of the list, with the ability to extend the list.
    >>> list1 = [1,2,3] >>> list2 = [4,5,6]>>> list1.extend(list2)>>> list1[1, 2, 3, 4, 5, 6]
  • Index () Gets the indexed value, and when we know the value of a sequence without knowing what the period subscript is, you can use the INDEX function
    >>> list1[1, 2, 3, 4, 5, 6]>>> list1.index(4)3
  • Reverse () Reverse sequence order
    >>> list1 = [1,2,3,4,5,6] >>> list1.reverse()>>> print(list1)[6, 5, 4, 3, 2, 1]
  • Sort () sorting
    >>> list1 = [1,9,3,7,2,6,0]>>> list1.sort()>>> list1[0, 1, 2, 3, 6, 7, 9]>>> list1.sort(reverse=True) >>> list1[9, 7, 6, 3, 2, 1, 0]
  • Len () gets the sequence length
    >>> len(list1)7
  • Max () Gets the maximum value of the sequence
    >>> max(list1)9
  • Min () Gets the minimum value of the element
    >>> min(list1)0
  • List () applies to all types of sequences. Strings cannot be modified like lists, so it is sometimes useful to create lists from strings
    >>> h = list("hello")>>> h[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘]
  • Join () to convert a list of strings into a string
    >>> ‘‘.join(h)‘hello‘
    Tuples tuple, read-only list

    Tuples use () definitions, and elements in () are separated by commas. Tuples can also get the value of an element through indexes and slices, just as in a list.

Dictionary Dictionary

The dictionary is the only type of mapping in Python, where data is stored out of order in the form of key-value pairs, the keys are not modifiable, and the values can be modified.

Create method: Use {} to define a dictionary

>>> dic = {‘name‘:‘wt‘}>>> dic=dict(([‘name‘,‘wt‘],[‘a‘,‘b‘],))

Initialize the value of the dictionary:

>>> all_star = dict.fromkeys([‘work‘,‘hobby‘],‘basketball‘)>>> print(all_star){‘work‘: ‘basketball‘, ‘hobby‘: ‘basketball‘}
Dictionaries also support additions and deletions to search

Increase

  • Example
    >>> dic1 = {‘name‘:‘wt‘}>>> dic1[‘age‘] = 21>>> dic1{‘name‘: ‘wt‘, ‘age‘: 21}

    Change: Here are 3 ways to change

  • example
     >>> dic1{' name ': ' WT ', ' age ': +} #直接对键进行赋值, modified, not created >> > dic1[' name '] = ' Kobe ' >>> dic1{' name ': ' Kobe ', ' age ': +}  
      
      #update方法, when there is an update in the Dic1 dictionary, Do not add key-value pairs in the Dic2 dictionary to dic1 >>> dic1 = {' name ': ' Kobe ', ' age ':21}>>> dic2 = {' name ': ' TMAC ', ' hobby ': ' Basketball '}>>> dic1.update (dic2) >>> dic1{' name ': ' TMAC ', ' age ': +, ' hobby ': ' Basketball '}  /pre> 

    Check:

  • Example
    >>> dic1 = {‘name‘: ‘TMAC‘, ‘age‘: 21, ‘hobby‘: ‘basketball‘}#获取指定键的值>>> dic1[‘name‘]‘TMAC‘
    #通过keys方法获取字典包含的键>>> dic1.keys()dict_keys([‘name‘, ‘age‘, ‘hobby‘])
    #通过values()方法获取字典的值>>> dic1.values()dict_values([‘TMAC‘, 21, ‘basketball‘])
    #通过items()方法获取字典的所有键值对>>> dic1.items()dict_items([(‘name‘, ‘TMAC‘), (‘age‘, 21), (‘hobby‘, ‘basketball‘)])

    By deleting:

  • Example
    >>> dic1{‘name‘: ‘TMAC‘, ‘age‘: 21, ‘hobby‘: ‘basketball‘}#使用del命令删除指定键的值>>> del dic1[‘hobby‘]>>> dic1{‘name‘: ‘TMAC‘, ‘age‘: 21}
    #clear()方法清空字典>>> dic1.clear()>>> dic1{}
    #pop()方法删除指定键的值,并返回该值>>> dic1 = {‘name‘:‘Kobe‘,‘age‘:21}>>> dic1.pop(‘name‘)‘Kobe‘>>> dic1{‘age‘: 21}
    #popitem()方法随机删除键值对,并返回删除的键值对>>> dic1 = {‘name‘:‘Kobe‘,‘age‘:21}>>> dic1.popitem()(‘age‘, 21)

    Dictionary nesting: Dictionaries can contain dictionaries, lists, and so on.

    books = {"日本作家" : {"村上春树":["且听风吟","没有女人的男人们","1Q84","多崎作"],"井上靖":["敦煌"],"东野圭吾":["白夜行","解忧杂货铺","放学后"]},"欧美作家" : {"昆德拉":["庆祝无意义","不能承受生命之轻"],"菲茨杰拉德":["了不起的盖茨比"]},"中国作家" : {"路遥":["平凡的世界","人生"],"金庸":["天龙八部","射雕英雄传","笑傲江湖"]}}>>> print(books[‘日本作家‘][‘村上春树‘][1])没有女人的男人们

    Dictionary sort: Dictionary By default sort by key, list sorted by value

    >>> dic1 = {24:‘Kobe‘,1:‘TMAC‘,30:‘Curry‘,23:‘LBJ‘}>>> dic1{24: ‘Kobe‘, 1: ‘TMAC‘, 30: ‘Curry‘, 23: ‘LBJ‘}#字典默认按键排序>>> print(sorted(dic1.items()))[(1, ‘TMAC‘), (23, ‘LBJ‘), (24, ‘Kobe‘), (30, ‘Curry‘)]
    #按值排序>>> print(sorted(dic1.values()))[‘Curry‘, ‘Kobe‘, ‘LBJ‘, ‘TMAC‘]

    Use a For loop to print the dictionary's key values

    #打印键>>> for i in dic1:...   print(i)... 2413023
    #打印键值>>> for i in dic1:...   print(i,dic1[i])... 24 Kobe1 TMAC30 Curry23 LBJ

The use of a list tuple dictionary for Python data structures

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.