Python Learning Path-fifth day-python data structure

Source: Internet
Author: User

Data structure 1. List
    • Example:
#!/usr/bin/python# Filename: using_list.py# This is my shopping listshoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]print ‘I have‘, len(shoplist),‘items to purchase.‘print ‘These items are:‘, # Notice the comma at end of the linefor item in shoplist:    print item,print ‘\nI also have to buy rice.‘shoplist.append(‘rice‘)print ‘My shopping list is now‘, shoplistprint ‘I will sort my list now‘shoplist.sort()print ‘Sorted shopping list is‘, shoplistprint ‘The first item I will buy is‘, shoplist[0]olditem = shoplist[0]del shoplist[0]print ‘I bought the‘, olditemprint ‘My shopping list is now‘, shoplist
    • Results
$ python using_list.pyI have 4 items to purchase.These items are: apple mango carrot bananaI also have to buy rice.My shopping list is now [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘, ‘rice‘]I will sort my list nowSorted shopping list is [‘apple‘, ‘banana‘, ‘carrot‘, ‘mango‘, ‘rice‘]The first item I will buy is appleI bought the appleMy shopping list is now [‘banana‘, ‘carrot‘, ‘mango‘, ‘rice‘]
    • You can add any kind of object in the list

    • For in implements the traversal of the list

    • Append method to add a new object

    • The Sort method can sort the list, which is a modification to the list itself

    • The Del method is followed by any location in the list, and you can delete the object

2. Tuples
    • Tuples and lists are similar in form, but objects in tuples are not allowed to be modified

    • Tuples that contain 0 or 1 objects are special: an empty tuple consists of a pair of empty parentheses, such as Myempty = (). 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,).

    • Tuples are typically used to print statements:

    • Example:

#!/usr/bin/python# Filename: print_tuple.pyage = 22name = ‘Swaroop‘print ‘%s is %d years old‘ % (name, age)print ‘Why is %s playing with that python?‘ % name
$ python print_tuple.pySwaroop is 22 years oldWhy is Swaroop playing with that python?
    • Similar to print statements in C, but not comma separated in python, directly with% customization

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

3. Dictionaries
    • The dictionary is actually key-value.

    • Example:

#!/usr/bin/python# Filename: using_dict.py# ‘ab‘ is short for ‘a‘ddress‘b‘ookab = {       ‘Swaroop‘   : ‘[email protected]‘,             ‘Larry‘     : ‘[email protected]‘,             ‘Matsumoto‘ : ‘[email protected]‘,             ‘Spammer‘   : ‘[email protected]‘     }print "Swaroop‘s address is %s" % ab[‘Swaroop‘]# Adding a key/value pairab[‘Guido‘] = ‘[email protected]‘# Deleting a key/value pairdel ab[‘Spammer‘]print ‘\nThere are %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‘]
    • Results:
$ python using_dict.pySwaroop‘s address is [email protected]There are 4 contacts in the address-bookContact 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]
    • The items method returns a list of tuples, with keys and values in each list, as above for loop traversal

    • The in method or the Has_key method can verify whether the key exists

Sequence

The above list, the tuple, the dictionary are the sequence, all have the various methods of the sequence, the sequence is including the index operation and the slicing operation;

Example:

  #!/usr/bin/python# Filename:seq.pyshoplist = [' Apple ', ' mango ', ' carrot ', ' banana ']# indexing or ' Subscription ' Operationprint ' item 0 is ', Shoplist[0]print ' item 1 are ', Shoplist[1]print ' Item 2 is ', Shoplist[2]print ' It  Em 3 is ', Shoplist[3]print ' Item-1 is ', Shoplist[-1]print ' Item-2 are ', shoplist[-2]# slicing on a listprint ' Item 1 to 3 Is ', Shoplist[1:3]print ' item 2 to end are ', Shoplist[2:]print ' item 1 to-1 is ', Shoplist[1:-1]print ' item start to end I  S ', shoplist[:]# slicing on a stringname = ' swaroop ' print ' characters 1 to 3 are ', Name[1:3]print ' characters 2 to end are ', Name[2:]print ' characters 1 to-1 is ', name[1:-1]print ' characters start-to-end is ', name[:]  
$ python seq.pyItem 0 is appleItem 1 is mangoItem 2 is carrotItem 3 is bananaItem -1 is bananaItem -2 is carrotItem 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 wacharacters 2 to end is aroopcharacters 1 to -1 is waroocharacters start to end is swaroop
    • Index Needless to say, subscript starting from 0, 1 means 1 from right to left, (in fact, I remember, the length of the sequence plus this value, is his real subscript)

    • The slice symbol ': ' is a flag, including the first operand, not including the second one, that is, left closed right open

    • Left operand is empty, starting from start position, right operand is empty, end position ends

Reference

Here's an example:

#!/usr/bin/python# Filename: reference.pyprint ‘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‘, shoplistprint ‘mylist is‘, mylist# notice that both shoplist and mylist both print the same list without# the ‘apple‘ confirming that they point to the same objectprint ‘Copy by making a full slice‘mylist = shoplist[:] # make a copy by doing a full slicedel mylist[0] # remove first itemprint ‘shoplist is‘, shoplistprint ‘mylist is‘, mylist# notice that now the two lists are different
$ python reference.pySimple Assignmentshoplist is [‘mango‘, ‘carrot‘, ‘banana‘]mylist is [‘mango‘, ‘carrot‘, ‘banana‘]Copy by making a full sliceshoplist is [‘mango‘, ‘carrot‘, ‘banana‘]mylist is [‘carrot‘, ‘banana‘]

From the above note we can see that the direct use = Connection assignment is equivalent to the direct copy of the address, the original sequence changes, the corresponding assignment of the sequence will also change, but the assignment is assigned by the sequence of the slice operation, change the original sequence will not affect the assignment of the sequence

Python Learning Path-fifth day-python 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.