Python Study Notes (7): Data Structure

Source: Internet
Author: User

Python has three built-in data structures-list, tuples, and dictionary.

1. List)

The list is represented by a pair of square brackets []. each item is separated by a comma. Once you create a list, you can add, delete, or search for it. So the list can be changed.

1) create a list
shoplist = ["apple", "mango", "carrot", "banana"]print("I have", len(shoplist), "items to purchase.")
2) Traversal
for item in shoplist:    print(item)
3) add data
print("I also have to buy rice.")shoplist.append("rice")print("My shopping list is now", shoplist)
4) sorting
shoplist.sort()print("Sorted shopping list is", shoplist)
5) Search
print("The first item I will buy is", shoplist[0])
6) delete data
olditem = shoplist[0]del shoplist[0]print("I bought the", olditem)print("My shopping list is now", shoplist)
2. tuples

Tuples are similar to lists, but they cannot be modified. Tuples are represented by a pair of parentheses (), and each item is separated by a comma. Tuples are usually used to securely use a group of values for statements or user-defined functions. That is, the values of the used tuples do not change.

zoo = ("wolf", "elephant", "penguin")print("Number of animals in the zoo is", len(zoo))new_zoo = ("monkey", "dolphin", zoo)print("Number of animals in the new zoo is", len(new_zoo))print("All animals in new zoo are", new_zoo)print("Animals brought from old zoo are", new_zoo[2])print("Last animal brought from old zoo is", new_zoo[2][2])

Tuples have the same index operators as lists. Tuples that contain 0 or 1 project. An empty tuples consist of an empty pair of parentheses, such as myempty = (). However, tuples containing a single element are not that simple. You must be followed by a comma in the first (unique) project so that python can distinguish between a tuple and an object with parentheses in the expression. That is, if you want a tuples containing project 2, you should specify Singleton = (2 ,).

The most common usage of tuples is to use them in print statements.

age = 22name = "Swaroop"print("%s is %d years old" % (name, age))print("Why is %s playing with that python?" % name)

% S indicates a string, and % d indicates an integer.

3. Dictionary (dict)

A dictionary is a set of key-value pairs. Keys must be unique. Note that you can only use immutable objects (such as strings) as Dictionary keys, but you can use immutable or variable objects as Dictionary values. The dictionary is represented by a pair of curly braces {}. Each key-value pair is separated by a comma, and key-value pairs are separated by a colon.

1) create a dictionary
ab = {"user1" : "user1@test.com", "user2" : "user2@test.com"}
2) Traversal
for name, address in ab.items():    print("Contact %s at %s" % (name, address))
3) add data
if not "tom" in ab:#OR not ab.has_key("tom")    ab["Tom"] = "tom@test.com"
4) Search
print("user1's address is %s" % ab["user1"])
5) Delete
del ab["tom"]
4. Sequence

Lists, tuples, and strings are sequences. The index operators and slice operators are two main features of sequences. The index operator allows us to capture a specific item from the sequence. The Slice operator allows us to obtain a slice of a sequence, that is, a part of the sequence.

#Indexing or "Subscription" operationprint("Item 0 is", shoplist[0])print("Item -1 is", shoplist[-1])#Slicing on a listprint("Item 1 to 3 is", shoplist[1:3])print("Item 2 to end is", shoplist[2:])print("Item 1 to -1 is", shoplist[1:-1])print("Item start to end is", shoplist[:])#Slicing on a stringname = "known"print("charactor 1 to 3 is", name[1:3])

The index can also be a negative number. In that case, the position is calculated from the end of the sequence. Therefore, shoplist [-1] indicates the last element of the sequence, while shoplist [-2] captures the second to last item of the sequence.

The Slice operator is a sequence name followed by a square bracket, which contains an optional number and is separated by a colon. Note that this is very similar to the index operator you are using. Remember that numbers are optional, while colons are required.
The first number (before the colon) in the slice operator indicates the start position of the slice, and the second number (after the colon) indicates the end of the slice. If the first number is not specified, Python starts from the beginning of the sequence. If the second number is not specified, Python stops at the end of the sequence. Note that the returned sequence starts from the starting position and ends just before the ending position. That is, the start position is included in the sequence slice, and the end position is excluded from the slice.

5. Objects and references
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 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", shoplist)print("mylist is", mylist)# notice that now the two lists are different

Output result:

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"]

6. String Functions
name = "Swaroop" # This is a string objectif name.startswith("Swa"):    print("Yes, the string starts with 'Swa'")if "a" in name:    print("Yes, it contains the string 'a'")if name.find("war") != -1:    print("Yes, it contains the string 'war'")delimiter = "_*_"mylist = ["Brazil", "Russia", "India", "China"]print(delimiter.join(mylist))

Output result:

Yes, the string starts with 'swa'
Yes, it contains the string 'A'
Yes, it contains the string 'war'
Brazil _ * _ Russia _ * _ India _ * _ China

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.