An example is provided to illustrate the usage of the list Data Structure in Python and the python data structure.
Loop and list
In any case, the program will do some repetitive tasks. Next we will print a list variable with a for loop. During this exercise, you must understand their meanings and functions.
Before using the for loop, we need to save the value of the loop. The best way is to use a list. The list is the container that stores data in order, which is not very complex, it is just a new syntax. The structure is as follows:
hairs = ['brown', 'blond', 'red']eyes = ['brown', 'blue', 'green']weights = [1, 2, 3, 4]
A list starts with a [sign. The elements in the list are separated by a comma, which is like a function parameter and ends with a]. python includes all the elements in a variable.
Let's take a look at some lists and print them cyclically:
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'domes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print "I got %r" % i # we can also build lists, first start with an empty on elements = [] # then use the range function to do 0 to 5 counts for i in range(0, 6): print "Adding %d to the list." % i # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print "Elements was: %d" % i
Running result
root@he-desktop:~/mystuff# python ex32.py
This is count 1This is count 2This is count 3This is count 4This is count 5A fruit of type: applesA fruit of type: orangesA fruit of type: pearsA fruit of type: apricotsI got 1I got 'pennies'I got 2I got 'domes'I got 3I got 'quarters'Adding 0 to the list.Adding 1 to the list.Adding 2 to the list.Adding 3 to the list.Adding 4 to the list.Adding 5 to the list.Elements was: 0Elements was: 1Elements was: 2Elements was: 3Elements was: 4Elements was: 5
Elements in the access list
List is very useful, so we need to know how to use it, so how do we access the elements in the List? The following shows how to access the first element of the list:
animals = ['bear', 'tiger', 'penguin', 'zebra']bear = animals[0]
Do we use 0 to obtain the first element? How does this work? It seems strange that a list starts from 0 in python, but it has many advantages. This is a rule for the time being.
This shows the differences between the numbers used in the program and the numbers used in the program.
Imagine that we had these four Animals compete in a race and sort them in the list according to their rankings. If your friend wants to know who wins, he will say, "Who is the 0th winner? "Of course not. He will say," Who is the first? "
This also illustrates the importance of sorting. If there is no first, there is no second statement, and if there is no second, there is no third. In addition, it is impossible for 0th people to exist. 0 indicates no. How can we make it impossible to win the game? This is unreasonable. We call these numbers ordered numbers because they differ in order.
Of course, programmers don't think about this because they can extract elements from the list. For programmers, the list above will think about a pile of cards. If they want a tiger, they can fetch the tiger. If they want a zebra, they can get a zebra. If you want to randomly obtain any element, you need to give each element an address, or an index. The best way is to start from 0 and then arrange it in order, in this way, we can take any element, even 0th.
For example, if you want the third animal, you can use 3 minus 1 to get index 2. Then you can get the third animal.
Remember: sequence number = Order 1, base number = 0
Let's do an exercise to write out the corresponding animals through the serial number and base value provided by me. Remember, first, second indicates the sequence number, and single digit indicates the base number.
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
The animal at 1.The 3rd animal.The 1st animal.The animal at 3.The 5th animal.The animal at 2.The 6th animal.The animal at 4.
The answer format is as follows: the first animal is on The 0th, And it is bear.
List operations
If we only know how to use the list append method, we do not actually know the usage of this function. Let's take a look at its usage.
When we use mystuff. append ('hello'), a series of things occur. Let's see what happened:
Python will first check the mystuff variable to see if it is a function parameter or a global variable. Find mystuff first.
When mystuff uses the. Number, it first looks at what the variable mystuff is. If it is a list, there will be many of its methods available.
When using append, you will find whether mystuff has the 'append' name. If yes, you can use it directly.
If the append is followed by parentheses, you will know that it is a function. Just execute this function as usual and there will be additional parameters.
This extra parameter is mystuff. It's strange, but python does this. The final function is like this: append (mystuff, 'Hello ').
In most cases, you don't have to know what is going on, but it helps when you encounter the following error:
root@he-desktop:~# pythonPython 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2Type "help", "copyright", "credits" or "license" for more information.
>>> class Thing(object):... def test(hi):... print "hi"... >>> a = Thing()>>> a.test("hello")Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: test() takes exactly 1 argument (2 given)>>>
The exercises below are to mix strings and lists to see if we can find something interesting.
ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there's not 10 things in that list, let's fix that." stuff = ten_things.split(" ") more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print "Adding:", next_one stuff.append(next_one) print "Thing's %d items now." % len(stuff) print "There we go:", stuff print "Let's do some things with stuff." print stuff[1] print stuff[-1] # print stuff.pop() print ' '.join(stuff) print '#'.join(stuff[3:5])
Running result
root@he-desktop:~/mystuff# python ex38.py
Wait there's not 10 things in that list, let's fix that.Adding: BoyThing's 7 items now.Adding: GirlThing's 8 items now.Adding: BananaThing's 9 items now.Adding: CornThing's 10 items now.There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']Let's do some things with stuff.OrangesCornCornApples Oranges Crows Telephone Light Sugar Boy Girl BananaTelephone#Light
Articles you may be interested in:
- List generator learning tutorial in Python
- How to convert a list into a dictionary data structure using Python
- Python generator expression and list Parsing
- Reverse, sort, and sorted
- Example of how to sort tuples and lists by conditions in Python
- A preliminary understanding of list and bitwise operators in Python
- Differences between list generators and generators in Python
- Differences between extend and append in python list operations
- How to append an element to a list in python
- Comparison of map and list derivation efficiency in Python
- Python calls function instances using the ancestor and list through apply
- In-depth analysis of list and its slicing and iteration operations in Python