Python Basics Five

Source: Internet
Author: User

The data structure is basically --- they can handle some data structures. Alternatively, they are used to store a set of related data.

PYthon has three built-in data structures --- lists, ganso, and dictionaries.

We will learn how to use them, and how they can make programming easier.

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. Imagine you have a shopping list that says what you want to buy, and you can easily understand the list. Just on your shopping list, it's possible that everything is on its own, and in python , you're separating each item with a comma.

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.

Quick start for objects and classes

Although I have been postponing the discussion of objects and classes, a little explanation of them now gives you a better understanding of the list.

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 5, you can assume that you have created an object (instance) of a class (type) int . in fact, You can look at help(int) to get a better understanding of this.

Classes also have methods that define only the ground function for a class. You can use these features only when you have an object of that class. For example, python provides the Append method for the list class , which lets you add an item at the end of the list. For example, Add that string to the list of my List.append (' an item ') MyList . Note that you use the point number to use the object's methods.

A class also has a domain, which is simply a variable defined for a class. You can use these variables/names only when you have an object of that class . Classes are also used with dot numbers, such as mylist.field.

#This is my shopping list

shoplist=[' apple ', ' mango ', ' carrot ', ' banana ']

print ' I has ', Len (shoplist), ' items to purchase '

print ' These items is: ', #notice the comma at end

For item in Shoplist:

Print Item,

print ' \ni also has to buy rice '

Shoplist.append (' rice ')

print ' My shopping list is now ', shoplist

print ' I'll sort my list now '

Shoplist.sort ()

print ' sortted shopping list is ', shoplist

print ' The first item I'll buy is ', shoplist[0]

OLDITEM=SHOPLIST[0]

Del Shoplist[0]

print ' I bought the ', Olditem

print ' My shooping list is Noew ', shoplist

Output:

$ python using_list.py

I have 4 items to purchase.

These items are:apple Mango carrot Banana

I also has to buy rice.

My shopping list is now [' Apple ', ' mango ', ' carrot ', ' banana ', ' rice ']

I'll sort my list now

Sorted shopping list is [' Apple ', ' banana ', ' carrot ', ' mango ', ' rice ']

The first item I'll buy is Apple

I bought the apple

My shopping list is now [' banana ', ' carrot ', ' mango ', ' rice ']

the variable shoplist is a list of someone's shopping. In the shop list, we only store the string of the names of the things that are purchased , but remember that you can add any kind of object including numbers or even other lists to the list.

We also used the for. in loops recursively between items in the list. From now on, you must have realized that the list is also a sequence.

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. It's a bit ugly, but it's really simple and effective.

Next, we use the append method to add a project to the list, just like the one we discussed earlier. We then verify that the item is actually added to the list by printing the contents of the list. The Print list simply passes the list to the print statement, and we can get a neat output.

Next, we use the Sort method of the list to sort the list. It is necessary to understand that this method affects the list itself, rather than returning a modified list --- this is different from how the string works. This is what we call the list to be mutable and the string immutable.

Finally, but when we finished buying something in the market, we wanted to remove it from the list. We use the DEL statement to do the work. Here, we point out which item in the list we want to delete, and the del statement removes her from the list for us. We indicate that we want to delete the first element in the list, so we use del shoplist[0]

If you want to know all the methods defined by the list object, you can get complete knowledge through Help (list).

Meta-group

Tuples and lists are very similar, except that tuples and strings are immutable, i.e. you cannot modify tuples. Tuples are defined by a comma-delimited 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.

zoo= (' Wolf ', ' Elephant ', ' penguin ')

print ' number of animals in the zoo is ', Len (Zoo)

new_zoo= (' monkey ', ' Dolphin ', zoo)

print ' number is ', Len (New_zoo)

print ' All Anima is ', New_zoo

print ' animals brought from the old Zoo Arer ', new_zoo[2]

print ' The last from Lod Zoo is ', new_zoo[2][2]

Output:

$ python using_tuple.py

Number of animals in the zoo is 3

Number of animals in the new zoo is 3

All animals in New Zoo is (' monkey ', ' Dolphin ', (' Wolf ', ' Elephant ', ' penguin ')

Animals brought from the old Zoo is (' Wolf ', ' Elephant ', ' penguin ')

Last animal brought from the old Zoo is Penguin

Variable Zoo is a tuple, and we see that the Len function can be used to get the length of the tuple. This also indicates that tuples are a sequence.

As the old zoo was closed, the relocation to the new zoo. Because the new-zoo tuple contains some of the animals that are already there and oh can be brought over by the old zoo. Back to the topic, notice that tuples within tuples do not lose their identities.

We can access the items in a tuple by using a square bracket to specify the location of an item, just as we use the list. This is called the index operator. We use new_zoo[2] to access the third item in New_zoo. We use new_zoo;2][2] to access the third item of the third project of the New_zoo tuple.

A tuple that contains 0 or 1 items. An empty tuple consists of a pair of empty parentheses. such as myemoty= (). However, tuples that contain a single element are less simple. You must follow the first (only) item followed by a comma so that python can differentiate between tuples and a Parenthesized object in an expression. That is, if you want a tuple containing item 2 , you should indicate singleton= (2,).

The idea of keeping objects at all times

Age=22

Name= ' Swaroop '

print '%s '%s years old '% (name,age)

Print ' Why are%s playing with Thar python '%name

$ python print_tuple.py

Swaroop is from years old

Why are swaroop playing with that python?

The print statement can use the string that follows the% symbol for the item tuple. These strings have a custom function. Customization lets the output meet a specific format. The customization can be%s to represent a string or%d to represent an integer. Tuples must correspond to these customizations in the same order.

Observing the first tuple we used, we first used%s, which corresponds to the variable name, which is the first item in the tuple. The second customization is%d, which corresponds to the second item of the tuple age

What Python does here is to convert each item in the tuple into a string and replace the custom location with the value of the string. Therefore,%s is replaced with the value of the variable name, and so on.

This usage of print makes it extremely easy to write output, which avoids many string manipulations. It also avoids the comma that we have been using for a long time.

Most of the time, you can just use the%s customization and let Python take care of the rest. The logarithm of this method also works. However, you may want to use the correct customization so that you can avoid the correctness of one layer of inspection procedures.

In the second print statement, we used a custom, followed by a single item after the% symbol-no parentheses. This only works when there is only one customization in the string.

Dictionary

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

Note that you can only use immutable objects ( such as strings ) as keys to the dictionary, but you could make immutable or mutable objects the values of the dictionaries. Basically, you should only use simple objects as keys.

Key-value pairs are tagged in the dictionary in such a way:D={key1:value1,key2:value2}. Note that their key-value pairs are separated by colons, and each pair is separated by commas, all of which are included in curly braces.

Remember that the key-value pairs in the dictionary are not sequential. If you want a specific shun, then you should sort them yourself before using them.

A dictionary is an instance / object of the Dict class

ab={' Swaroop ': ' [email protected] ',

' Larr ': ' [email protected] ',

' SD ': ' [email protected]/sd '}

print ' Swaroop address is%s '%ab[' Swaroop ']

#adding a Key/value pair

ab[' Guido ']= ' [email protected] '

#delet a Key/value pair

Del ab[' Larr ']

print ' \nthere is%d contacts in the address-book\n '%len (AB)

For name,address in Ab.items ():

print ' Contact%s at%s '% (name,address)

If ' Guido ' in AB: #or ab.has_key (' Guido ')

Print "\nguido s address is%s"%ab[' Guido ']

Output ;

$ python using_dict.py

Swaroop ' s address is [email protected]

There is 4 contacts in the Address-book

Contact Swaroop at [email protected]

Contact Matsumoto at [email protected]

Contact Larry at [email protected]

Contact Guido at [email protected]

Guido ' s address is [email protected]

We created the field ab using the tags we discussed. then we use the key-value pair by specifying the key using the index operators discussed in the list and tuple chapters.

We can use the index operator to address a key and assign it a value, thus adding a new key-value pair.

We can use the DEL statement to delete a key-value pair. We just need to specify the dictionary and use the index operator to indicate which keys to delete, and then pass them to the del statement. When we do this, we don't need to know which key corresponds to the value.

Next, use the dictionary's items method to use each key-value pair in the dictionary. This returns a list of tuples, each of which contains a pair of items--a key- value pair that we crawl, and then assign to for . The variables in the in loop name and address then print the 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 .

Keyword parameters and dictionaries. If you look at the keyword arguments you use in the function in a different way, you've already used a dictionary! Just think about --the key-value pairs that you use in the parameter list of the function definition. When you use a variable in a function, it is simply a key to the dictionary ( which is called the symbol table in the compiler-designed terminology )

Sequence

Lists, tuples, and strings are all Xu, 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 lets you grab a specific item from the sequence. The slice operator allows us to get a slice of the sequence, which is part of the sequence.

shoplist=[' apple ', ' mango ', ' carrot ', ' banana ']

#indexing or ' subscription ' operation

print ' Item0 is ', shoplist[0]

print ' item1 is ', shoplist[1]

print ' item2 is ', shoplist[2]

print ' Item3 is ', shoplist[3]

print ' item-1 is ', shoplist[-1]

print ' Item-2 is ', shoplist[-2]

#Slicing on a list

print ' Item 1 to 3 is ', Shoplist[1:3]

print ' Item 2 to end ', Shoplist[2:]

print ' Item 1 to-1 is ', shoplist[1:-1]

print ' item start to end ', shoplist[:]

#slicing on a string

Name= ' Swarroop '

print ' characters 1 to 3 ', Name[1:3]

print ' characters 2 to end ', Name[2:]

print ' characters 1 to-1 is ', name[1:-1]

print ' characters start to end ', name[:]

Output:

$ python seq.py

Item 0 is Apple

Item 1 is Mango

Item 2 is carrot

Item 3 is Banana

Item-1 is banana

Item-2 is carrot

Item 1 to 3 is [' Mango ', ' carrot ']

Item 2 to end is [' carrot ', ' banana ']

Item 1 to-1 is [' Mango ', ' carrot ']

Item start to end is [' Apple ', ' mango ', ' carrot ', ' banana ']

Characters 1 to 3 is WA

Characters 2 to end are Aroop

Characters 1 to-1 is Waroo

Characters start to end is Swaroop

First, let's learn how to use an index to get a single item in a sequence. This is also known as the following table to rub Europe. Whenever you use a number in square brackets to specify a sequence,python fetches the items in the corresponding position in the sequence for you. python starts counting from 0. shoplist[0] crawl the first item.

The index can also be negative, in which case the position is calculated from the end of the sequence. Thus,shopList[-1] represents the last element of the sequence and the fourth element in the shoplist sequence.

The go to slice operator is a sequence name followed by a square bracket, with a bunch of optional numbers in square brackets, separated by a colon. Note that this is very similar to the index operator you are using. Remember that the number is optional, and the colon is required.

The first number in the slice operator indicates that the slice starts as a child, and the second number indicates where the slice ends. If you do not specify the first number, the default starts from the beginning of the series. If you do not specify a second number, the pyThonhui 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 excluded from the slice.

This 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.

You can make slices with negative numbers. Negative numbers are used at the beginning of the end of the sequence. For example, shopList[:-1] returns a sequence slice that contains all items except the last item

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 artifact of the sequence is that you can access the tuples, lists, and strings in the same way,

Reference

When you create an object and assign a variable to it, the variable simply refers to that object, not the object itself! In other words, the variable name points to the memory of the object stored in your computer, which is called the name-to-object binding, and so-called pointers are also.

print ' Simple assignment '

shoplist=[' apple ', ' mango ', ' carrot ', ' banana ']

Mylist=shoplist#mylist is just another name pointing to the same object

Del Shoplist[0]

print ' Shoplist is ', shoplist

print ' MyList is ', mylist

#notice that both Shoplist and MyList both print the

#the same list

print ' Copy by making a full slick '

mylist=shoplist[:] #make a copy by doing a full slice

Del Mylist[0]

print ' Shoplist is ', shoplist

print ' MyList is ', mylist

#notice that now the lists is different

Output:

$ python reference.py

Simple assignment

Shoplist is [' Mango ', ' carrot ', ' banana ']

MyList is [' Mango ', ' carrot ', ' banana ']

Copy by making a full slice

Shoplist is [' Mango ', ' carrot ', ' banana ']

MyList is [' carrot ', ' banana ']

Just remember if you want to copy a list or a similar sequence or other complex object (not a simple object such as an integer ). Then you have to use the slice operator to get the copy. If you just want to use another variable name, all two names refer to the same object, and if you're not careful, it can cause a variety of problems.

The contents of more strings,

Name= ' Swarrop '

If Name.startswith (' SWA '):

print ' Yes, the string start with SWA '

If ' a ' in name:

print ' Yse '

If Name.find (' arr ')!=-1:

print ' Yes,it contains the string arr '

Delimiter= ' _*_ '

mylist=[' Brazil ', ' Russia ', ' India ', ' China ']

Print Delimiter.join (mylist)

Output:

$ python str_methods.py

Yes, the string starts with "Swa"

Yes, it contains the string "a"

Yes, it contains the string "War"

Brazil_*_russia_*_india_*_china

the starts with method detects the start of the given string. The In operator is used to verify that a given string is part of another string.

The Find method is used to give the string a position in another string, or 1 to indicate that the string cannot be found. The str class also has a neat method for items with a string join sequence as a delimiter , which returns a generated large string.

Python Basics Five

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.