Python Basic Learning 3---data structure

Source: Internet
Author: User

Data

The data structure is basically---that they can handle the structure of the data or that they are used to store a set of related data.

There are three types of built-in data structures in Python----- lists, tuples, and dictionaries

Listing (list)

List is like we want to go to the supermarket to buy things list, the need to buy things listed after the whole structure is the list of data, once created we can arbitrarily add delete modify operations so can be determined

List data is a mutable data type

A list is an example of using objects and classes. When you use the variable i and assign it a value, such as assigning an integer of 5, you can assume that you have created an object (instance) I of a class (type) int. In fact, you can look at help (int) to get a better understanding of this.

1Shoplist = ["Apple","Mango","Carrot","Banana"]2 3 Print "I have", Len (shoplist),"Item to purchase"4 5 Print"These items are:",6 7  forIteminchshoplist:8     PrintItem,9 Ten Print"\ n I also has to buy rice" OneShoplist.append ("Susan") A Print 'My Shopping list is now', Shoplist -  - Print 'I'll sort my list now' the Shoplist.sort () - Print'Sorted shopping list is', Shoplist -  - Print 'The first item I'll buy is', Shoplist[0] +Olditem =Shoplist[0] -  + delShoplist[0] A  at Print 'I bought the', Olditem - Print 'My Shopping list is now', shoplist

Now you have created an object of the list data type shoppinglist to add the deletions and invoke the class method operation.

Note that we used a comma at the end of the print statement to eliminate the line breaks that are automatically printed for each print statement. This is a bit
Ugly, but really simple and effective. Use characters such as "End" in the python3.x version to eliminate the wrap-around default action.

Meta-group

Tuples and strings are immutable, i.e. you cannot modify tuples. Tuples are defined in parentheses and commas, and tuples are typically used in statements or user-defined functions to safely adopt a set of time-worthy

That is, the value of the tuple being used does not change.

1Zoo = ('Wolf','Elephant','Penguin') #定义一个zoo的元组数据2 3 Print 'Number of animals in the zoo is', Len (Zoo) #打印元组数据的长度4 5New_zoo = ('Monkey','Doplhin', Zoo) #定义一个新的new_zoo类型的数据 before the zoo was included in6 Print 'Number OD Animals in the new zoo is', Len (new_zoo) #取得新的元组的长度7 8 Print 'animals brought fron old zoo is', new_zoo[2] #取得new_zoo中第三个数据 is the sequence data of the zoo9 Print 'Last animal brought from the old Zoo is', New_zoo[2][2] #取得new_zoo中第三个数据中的第三个数据 the third data in the zoo is Penguin

Contains a tuple of 0 or 1 item objectives. An empty tuple consists of a pair of empty parentheses, such as Myempty = (). However, it contains a single
Element's tuple is less simple. You must follow the first (only) item followed by a comma, so that python can differentiate between tuples
and an object with parentheses in the expression. That is, if you want a tuple containing item 2, you should refer to the
Ming singleton = (2,).

Tuple Print Statements

1 age =2'swaroop'34print'  %s is%d yearsold' % (name, age)

Dictionary

The dictionary is similar to the address book in the phone, that is, we enter the name key () and the detailed information (value) is linked together. Note the key must be unique as if we had two people who happened to have the same name, you wouldn't be able to find the right information.

Note: Only immutable objects such as strings can be used as keys to the dictionary, but you may have immutable or mutable objects as the values of the dictionary basically you should only use simple objects as keys.

The key-value pairs are tagged in the dictionary in such a way: d={key1:values1,key2:values2} Note that their key/value pairs are separated by colons and each pair is separated by commas all of which need to be included in curly braces.

Remember that the key/value pairs in the dictionary are not sequential if you want a particular order then you should sort them before you use them.

A dictionary is an instance/object of the Dict class

1AB = {'Swaroop' :2 '[email protected]',3 'Larry':'[email protected]',4 'Matsumoto':'[email protected]',5 'spammer':'[email protected]' # Create a new dictionary-type Object AB6 }7 Print "Swaroop ' s address is%s"% ab['Swaroop'] #检索出Swaroop的对象信息8 #Adding A Key/value pair add a new key value9ab['Guido'] ='[email protected]'Ten #Deleting a Key/value pair delete a key value that already exists One delab['spammer'] A Print '\nthere is%d contacts in the address-book\n'%Len (AB) -  forName, AddressinchAb.items (): -     Print 'Contact %s at%s'%(name, address) the if 'Guido' inchAb:#OR ab.has_key (' Guido ') -     Print "\nguido ' s address is%s"% ab['Guido']

Next, we use the dictionary's items method to use each key/value pair in the dictionary. This returns a list of tuples, each of which

Tuples contain a pair of items-the key and the corresponding value. We grab this pair and assign it to for. In the change in the loop
Volume name and address and print these values in the for-block.
We can use the in operator to verify the existence of a key/value pair, or to use the Has_key method of the Dict class. You can make
Use Help (Dict) to view a complete list of methods for the Dict class.

Sequence

Lists, tuples, and strings are sequences, but what are the sequences and why are they so special? The two main features of a sequence are index operators and slice operators . The index operator allows us to fetch a specific item from the sequence. The slice operator allows us to get a slice of the sequence, which is part of the sequence.

1Shoplist = ['Apple','Mango','Carrot','Banana']2 #indexing or ' Subscription ' Operation3 Print 'Item 0 is', Shoplist[0]4 Print 'Item 1 is', shoplist[1]5 Print 'Item 2 is', shoplist[2]6 Print 'Item 3 is', shoplist[3]7 Print 'Item-1 is', shoplist[-1]8 Print 'Item-2 is', shoplist[-2]9 #slicing on a listTen Print 'Item 1 to 3 is', Shoplist[1:3] One Print 'Item 2 to end is', shoplist[2:] A Print 'Item 1 to-1 is', shoplist[1:-1] - Print 'Item start to end is', shoplist[:] - #slicing on a string theName ='Swaroop' - Print 'characters 1 to 3 is', Name[1:3] - Print 'characters 2 to end', name[2:] - Print 'characters 1 to-1 is', name[1:-1] + Print 'characters start to end are', name[:]

Index operators and slice operators

1. The index operator is also called the subscript operator, which specifies a sequence with a number in parentheses, and Python automatically fetches the corresponding item in the sequence. It is important to note that index subscripts in Python can use negative numbers.

The position is calculated from the end of the queue, such as Shoplist[-1], which represents the last element.

2. The slice operator is a serial number followed by a square bracket, with a pair of optional digits enclosed in square brackets and separated by a colon. Note that this is very similar to the index operator used. It is necessary to remember that the number is an optional colon.

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 is
Beam. 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.
Note that the returned sequence starts at the start position and ends just before the end position. That is, the start position is contained in the sequence slice, and
The end position is rejected outside the slice.

Thus, Shoplist[1:3] returns a sequence slice starting at position 1, including position 2, but stopping at position 3, thus returning a
A slice containing two items. Similarly, shoplist[:] Returns a copy of the entire sequence.
You can make slices with negative numbers. Negative numbers are used at the beginning of the end of the sequence. For example, Shoplist[:-1] will return except for the last
A sequence slice that contains all items outside the project.
Use the Python interpreter to interactively try out different slices of the specified combination, i.e. you can see the results immediately at the prompt. The magic of the sequence
You can access tuples, lists, and strings in the same way.

Python Basic Learning 3---data structure

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.