The seventh lesson of Python introductory basics--sequence

    1 Introduction

    This chapter will enter a new concept - data structure, data structure is a combination of data elements organized together in some way. In Python, the most basic data structure is the sequence, and each element in the sequence is assigned a sequence number - the location of element, which is what we call the location of the element, also known as the index . The first is 0, the second is 1, and so on.

    Remember the array in C language? This powerful data structure, like strings, is often used by us when we write programs, and it is one of the difficulties we encounter, but this is not the case in Python. Remember why you want to learn Python? How do you feel when you know it. To put this question into the answer, you have to keep it firmly in mind and never forget your original intention!

Note: The python code generated in the HTML/XML editor will have a tag language similar to <span style= "color:#333333;" >, this part is not in the code, please ignore it automatically.

    2. Sequence operation method

    All sequence types can perform certain operations. These operations include: indexing, slicing, adding, multiplying, and checking membership . In addition to these basic must-haves, there are also calculating sequence lengths, finding the maximum value among sequence elements , the minimum standard library built-in functions, let's take a look at these magic methods or functions separately.

    one.index

    Remember what I said in the preface, the elements in the sequence are all numbered, starting from 0 and increasing. These elements can be accessed by their own numbers, see the example below.

>>> sequence="Hello,World!"
>>> sequence[0]
'H'
>>> sequence[-1]
'!'
>>>

    In this example, we initialize a string whose content is Hello, World! , in fact, a string is a sequence of characters. After initialization, we can access it. 0 means the first element starting from the leftmost, and -1 means the first element starting from the rightmost , the result of the program running is very clear and easy to understand. There is another operation, we have to know, look at the following program.

>>> 'Hello'[4]
'O'

    Isn't it amazing that string literals can refer to variables directly without needing to use a variable to refer to it. The following example program requires input of year, month, and day, and then prints out the month name of the corresponding date. Let's take a look

    Example:the_use_of_index.py

months=[
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'September',
    'October',
    'November',
    'December'
] #Initialize the list of months
endings=['st','nd','rd'] + 17*['th'] + ['st','nd','rd'] + 7*['th'] + ['st' ] #Remember: 1st, 2nd, 3rd? That's how it came. 
year= raw_input ('Year: ')
month=raw_input('Month(1-12): ')
day=raw_input('Day(1-31: ') #User input processing
month_number=int(month)
day_number=int(day) #Convert to the type we need

month_name=months[month_number-1]
ordinal=day + endings[day_number-1] #Corresponding to the appropriate month and day

print month_name + '' + ordinal + ',' + year #Splice output

    Understanding this procedure requires attention to the following points:

  • When initializing the months and endings lists, pay attention to the comparison between the element positions in the list and the number of months and days in real life, which is why we want to do this.
    month_name=months[month_number-1]
    ordinal=day + endings[day_number-1]
  • The use of raw_input() when user input is because I use the Python2.x interpreter on the one hand, and on the other hand, it is also for the user's consideration, which was mentioned in the previous chapter, I hope to remember.
  • The program is relatively simple on the whole, and the simple splicing method of the final string is also very easy to understand. Practice it yourself to get the final result.
/usr/local/bin/python2.7 /Users/yangjiayuan/PycharmProjects/day/day02/the_use_of_index.py
Year: 2018
Month(1-12): 5
Day(1-31: 2
May2nd, 2018

Process finished with exit code 0

    Two: Sharding

    We can access the elements in the sequence by index, but there is a problem: it seems that only one element can be accessed at a time. Look at the above example, it is indeed the case. To access more elements and return more elements, we need the help of sharding methods.

    Slicing operations are useful for extracting partial elements of a sequence. And it should be noted that the numbering of the elements is particularly important here. To use two indexes, use two indexes separated by colons to implement, see some examples.

>>> numbers=[1,2,3,4,5,6,7,8,9,10] #Initialize a numbers sequence.
>>> numbers[3:6] #Numbers are included before and after, um, you can experience it yourself.
[4, 5, 6]
>>> numbers[0:1]
[1]
>>> numbers[7:10] #Number 10 points to the 11th element, but the 11th element does not exist. what reason? The number is before and after, remember? In order for the shard part to contain the last element of the list, the corresponding index of the element next to the last element must be provided.
[8, 9, 10]
>>> numbers[-3:-1]
[8, 9]
>>> numbers[-3:0] #This is obviously not the result we want, as long as the leftmost index of the shard appears later in the sequence than its right, the result is an empty sequence
[]
>>> numbers[-3:] #There is a magic, if the part obtained by slicing includes the element at the end of the sequence, just empty the last index.
[8, 9, 10]
>>> numbers[:3] #The above magic is also applicable to the beginning
[1, 2, 3]
>>> numbers[:] #If you want to get all the elements in the sequence, it's very simple, just leave the two indices empty.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    Some children's shoes just think, I can have two indexes to get the elements I want, so three is not enough? congratulations! Of course, you can take a look at the little thing called step size. When sharding, the start and end positions of the shards need to be specified by themselves, and the step length parameter is hidden in the above operations, and it is also 1 by default. The slicing operation is to traverse the elements in the sequence according to the step size of 1, and then return all the elements between the start and end positions, and print them to the screen according to the user's needs. Let's take a look, of course, the step size cannot be 0, but it can be a negative number. When it is a negative number, you should pay attention to the position of the start and end of the index.

>>> numbers[0:10:1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> numbers[0:10:2]
[1, 3, 5, 7, 9]
>>> numbers[::4]
[1, 5, 9]
>>> numbers[8:3:-1]
[9, 8, 7, 6, 5]

    Three: add

    This part is very simple, just pay attention to the errors in the following program.   

>>> [1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]
>>> 'Hello' + 'World'
'HelloWorld'
>>> [1,2,3] + 'Hello'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

    TypeError: Lists and strings cannot be concatenated, although they are both sequences, only two sequences of the same type can be concatenated.

    Four: Multiply

Multiplying a sequence by a number n generates a new sequence in which the old sequence is repeated n times, very simple.

>>> 'Hello'*5
'HelloHelloHelloHelloHello'
>>> [1,2,3]*10
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

    Five: Check Membership

    Membership is checked in Python with the in operator, which checks whether a condition is true. Returns TRUE if true. Returns FALSE if false. Let's take a look at a program to deepen understanding.

>>>'p' in 'Python'
False
>>>'P' in 'Python'
True
database=[
    ['youzi','1234'],
    ['appple','5678'],
    ['banana','8888'],
    ['middle','6666']
]
username=raw_input('User name: ')
passwd=raw_input('Passwd: ')

if [username,passwd] in database:
    print 'Permission granted'
else:
    print 'Access denied'
/usr/local/bin/python2.7 /Users/yangjiayuan/PycharmProjects/day/day02/the_use_of_in.py
User name: Trump
Passwd: 1234
Access denied

Process finished with exit code 0
/usr/local/bin/python2.7 /Users/yangjiayuan/PycharmProjects/day/day02/the_use_of_in.py
User name: youzi
Passwd: 1234
Permission granted

Process finished with exit code 0

    six: some other methods

>>> sequence=[None]*10 #None is a built-in value of Python, which means "there is nothing here". If you don't want to occupy ten element space, you can use []
>>> sequence
[None, None, None, None, None, None, None, None, None, None]
>>> len(sequence) #len function returns the number of elements contained in the sequence
10
>>> numbers=[1,2,3,4,5,6,7,8,9,10]
>>> max(numbers) #return the largest element in the sequence
10
>>> min(numbers) #return the smallest element in the sequence
1
>>> max(1,2,3) #Here, the parameters of the max and min functions are not always sequences, and can also be multiple numbers directly as parameters
3
>>> min(4,5,6)
4
    Okay, let’s talk about this part of the sequence first. I need to find some examples to practice and practice to enhance the feel. Next chapter preview -- list.






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325776295&siteId=291194637