Data structure of Python basics

Source: Internet
Author: User

There are four built-in data structures in Python-lists, tuples, dictionaries, and collections.

1. List

A list is a data structure that handles a set of ordered items, that is, you can store a sequence of items in a list.

The items in the list should be enclosed in square brackets so that Python knows that you are specifying a list. Once you have created a list, you can add, delete, or search for items in the list. Since you can add or delete items, we say that the list is a mutable data type, that is, this type can be changed.

defList ():#list, orderedShoplist = ["Apple","Carrot","Banana","Mango"]    Print "I have", Len (shoplist),"items to purchase."    Print "These items are:",     forIinchshoplist:PrintI,Print "\ni alse has to buy rice."Shoplist.append ("Susan")#Append method to add an item to the list object    Print "My Shopping list is now", ShoplistPrint('I'll sort my list now') Shoplist.sort ()#sort the list by using the Sort method    Print "Sorted Shopping list is", ShoplistPrint "The first item I'll buy is", Shoplist[0]#like a one-dimensional arrayOlditem =Shoplist[0]delSHOPLIST[0]#del Remove this item    Print "I bought the", OlditemPrint "My Shopping list is now", shoplist

2. Tuples

Tuples are used to assemble a variety of objects together. Tuples and lists are very similar, except that tuples and strings are immutable, meaning that you cannot modify tuples. Tuples are defined by a comma-separated list of items in parentheses.

Tuples are typically used when a statement or user-defined function can safely take a set of values, that is, the value of the tuple being used does not change.

defTupel ():#tuples, non-modifiableZoo = ("Python","Mouse","Wolf")#, the connection effect    Print "Number of animals in the Zoo is:", Len (Zoo) Newzoo= ("Monkey","Panda", Zoo)Print "Number of cages in the New Zoo is:", Len (Newzoo)Print "All animals in New Zoo is:", NewzooPrint "Animals brought from the old Zoo is:", newzoo[2]    Print "Last animal brought from the old Zoo is:", Newzoo[2][2]#like a two-dimensional array    Print "Number of animals in the new Zoo is", Len (Newzoo) -1+len (newzoo[2])

3. Dictionaries

The dictionary is similar to the Address book where you find the address and contact details by contact name, that is, we associate the key (first name) with the value (details). Note that the key must be unique, as if two people happen to have the same name and cannot find the correct information.

Note that only immutable objects, such as strings, can be used as keys to the dictionary, but immutable or mutable objects are the values of the dictionary. Basically, you should only use simple objects as keys.

Key-value pairs are tagged in the dictionary in such a way that: D = key1:value1, key2:value2. There is no order for key/value pairs in the dictionary. If you want a particular order, then you should sort them yourself before using them.

A dictionary is an instance/object of the Dict class.

defKeyValue ():#DictionarySafe = {"Baidu":"Baidu.con",                 "Tenxun":"Tenxun.con",                "Ali":"Alibaba.com",                " the":"qihu360.com"}    Print "Safe ' s Address is:", safe["Baidu"]    delsafe[" the"]#Delete key/value pairs    Print "there is {0} Safe:". Format (len (Safe)) forName,addressinchSafe.items ():Print "{0} at {1}". Format (name,address) safe["Lvmeng"] ="lvmeng.com"     #so we're going to add it in.    if "Lvmeng" inchSafe:Print "Lvmeng ' s address is:", safe["Lvmeng"]

Using the dictionary's items method, which uses each key/value pair in the dictionary, returns a list of tuples, each of which contains a pair of items-the key and the corresponding value.

4. Sequence

Lists, tuples, and strings are sequences.

The main features of the sequence are the test of the cable members (for example, in and out of the expression) and the index operator, which allows us to fetch a specific item directly from the sequence.

defIndex ():#sequence, cable member validation, and index operatorsShoplist = ["Apple","Mange","Carret","Banana"] Name="Key"    Print "Item 0 is:", Shoplist[0]Print "Item-1 is:", Shoplist[-1]#come back.    Print "Character 0 is:", Name[0]Print "Character 1 is:", name[1]    Print "Item 1 to 3 is:", Shoplist[1:3]    Print "Item start to end is:", shoplist[:]Print "Character 1 to 3 is:", Name[1:3]    Print "Character start to end is:", name[:]

The index can also be negative, in which case the position is calculated from the end of the sequence.

The first number in the slice operator (preceded by a colon) indicates where the slice begins, and the second number (after the colon) indicates where the slice ends. If you do not specify the first number, Python starts from the beginning of the sequence. If you do not specify a second number, Python stops at the end of the sequence. The returned sequence starts at the starting position and ends just before the end position. That is, the start position is contained in the sequence slice, and the end position is excluded from the slice. Shoplist[1:3] Returns a slice that contains two items, starting at position 1, including position 2, but stopping a sequence slice at position 3. Similarly, shoplist[:] Returns a copy of the entire sequence.

5. Collection

Collections are aggregates of simple objects that have no order. The collection is used when the presence of an object in a cluster is more important than its order or number of occurrences. Using a collection, you can check whether it is a member, a subset of another collection, get the intersection of two collections, and so on.

defGather ():#CollectionCountry = Set ([" China","Russia","USA"])    "USA" inchCountry"India" inchCountry Countries=country.copy () Countries.add ("UK") Countries.issuperset (country) country.remove ("USA")

6. References

defQuote ():#References    Print "Simple Assignment"shoplist= ["Apple","Mango","Carret","Banana"] MyList=shoplistdelShoplist[0]Print "Shoplist is:", ShoplistPrint "MyList is:", MyList#just like C + +, the name is different, it represents the same piece of memory    Print "Copy by making a full slice"MyList=shoplistdelMylist[0]Print "Shoplist is:", ShoplistPrint "MyList is:", MyList

Data structure of Python basics

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.