Python from rookie to Master (12): Manipulating sequence elements by index

Source: Internet
Author: User

1. Defining a Sequence

This article describes how to define a sequence in the Python language. The syntax for defining a sequence is similar to an array in Java, using a pair of brackets to enclose the values of elements in the sequence.
The following example creates an element type that is a sequence of strings, implementing the Code as follows:

names = ["Bill", "Mary", "Jack"]

The same sequence can contain not only values of the same type, but also different types of values.
The following example places different types of values in a sequence, implementing the following code:

values = ["Bill", 30,12.5, True]

In the preceding code, the values sequence contains 4 element value, the 4 element values are different data types, namely the string ("Bill"), the Integer (30), the floating-point number (12.5), and the Boolean type.

Each element of a sequence can also be another sequence, which in fact is equivalent to a two-dimensional or multidimensional array.

This example creates a two-dimensional sequence, and the type of the element value for each sequence is a sequence.

names = ["Bill", "Mike"]numbers = [1,2,3,4,5,6]salary=[3000.0,4000.0,5000.0]flags = [True,False,True,True]values = [names,numbers,salary,flags,[‘a‘,‘b‘]] #  创建二维序列for value in values:                            #  输出二维序列    print(value)

The program runs as shown in the results.

2. Manipulating sequence elements by index

All elements in the sequence are numbered, and the numbering is incremented from 0 onwards. All elements in a sequence can be accessed by number, which is called an index.

The following example accesses and outputs the 1th and 3rd elements of a sequence names.

names = ["Bill", "Mary", "Jack"]print(names[0])         # 运行结果:Billprint(names[2])         # 运行结果:Jack

The program runs as shown in the results.

In the above code, the values of the 1th and 3rd elements in the names sequence are obtained by index 0 and index 2 respectively. Strings in the Python language can also get specific characters by index.

This example obtains and outputs the 1th and 4th characters in the string s through an index, and gets the 3rd character of "Apple".

s = "Hello World"print(s[0])             # 运行结果:Hprint(s[3])             # 运行结果:lprint("Apple"[2])           # 运行结果:p

The program runs as shown in the results.

In the preceding code, the 1th and 4th characters in the string s are obtained by index 0 and index 3, respectively. The 3rd character of the string "Apple" is then obtained by index 2.

A string entered through input can also refer to one of its characters through an index.
This example enters a year, and if you are interested only in the last character of the year, get the last digit that uses the index to intercept the year.

fourth = input(‘请输入年份:‘)[3]print(fourth)                   

The program runs as shown in the results.

If the index is a 0 or a positive integer, the Python language starts with the 1th element to the left of the sequence, and if the index is negative, the Python language starts with the 1th element to the right of the sequence. The index of the last element of the sequence is-1, the index of the 2nd element is-2, and so on.

This example gets the value of the 1th element in the names sequence by index, and the value of the 1th and penultimate elements in the names sequence through a negative index.

names = ["Bill", "Mary", "Jack"]print(names[0])             #  运行结果:Billprint(names[-1])                #  运行结果:Jackprint(names[-2])                #  运行结果:Mary

The program runs as shown in the results.

An exception is thrown when the index exceeds the index range of the sequence.

This example uses Indexes 4 and 4 to refer to the element values in the names sequence, both of which exceed the index range of the names sequence, so an exception is thrown. However, when the 1th exception is thrown, the subsequent statements are not executed.

names = ["Bill", "Mary", "Jack"]print(names[4])                     #  索引超出names序列的范围,将导致抛出异常print(names[-4])                        #  索引超出names序列的范围,将导致抛出异常

The program runs as shown in the results.

In the above code, either index 4 or index-4 exceeds the range of the names sequence index ( -3 <= index range <= 2), so an exception is thrown.

This example requires entering the year, month, and day, and converting the month to Chinese output, such as the input month is 4, which requires the output "April".

# 将中文月份放到序列中months = [    ‘一月‘,    ‘二月‘,    ‘三月‘,    ‘四月‘,    ‘五月‘,    ‘六月‘,    ‘七月‘,    ‘八月‘,    ‘九月‘,    ‘十月‘,    ‘十一月‘,    ‘十二月‘    ]year = input("年:")              # 输入年month = input(‘月(1-12):‘)           # 输入月day = input(‘日(1-31):‘)         # 输入日monthNumber = int(month)            # 将字符串形式的月转换为数值形式的月monthName = months[monthNumber - 1]                 # 从序列中获取中文的月份print(year + "年 " + monthName + " " + day + "日")        # 按指定格式输入年月日

The program runs as shown in the results.

"Python from rookie to Master" has been published, began to serial, buy send video lessons

Python from rookie to Master (12): Manipulate sequence elements by index

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.