Python basic tutorial Reading Notes (2) Chapter 2 list and metadata, python basic tutorial

Source: Internet
Author: User

Python basic tutorial Reading Notes (2) Chapter 2 list and metadata, python basic tutorial

2.1 Sequence Overview

The main difference between a list and a group is that a list can be modified, but a list cannot be modified. That is to say, if you want to add elements as required, the list may be better. For some reason, it is more appropriate to use tuples when the sequence cannot be modified. The reason for using the latter is generally technical, and it is related to the internal operation mode of Python. This is also why built-in functions may return tuples. In general, the list can replace tuples in almost all cases.

Compile a list:

>>> edward=['Edward Gumby',42]

It is also possible to construct the following list of individual employee information, which is your database:

>>> john=['John Simith',50]>>> database=[edward,john]>>> database[['Edward Gumby', 42], ['John Simith', 50]]

2.2 General sequence operations

All sequence types can perform certain operations. These operations include: Index, sliceing, adding, multiplying, and checking whether an element belongs to a Sequence member (membership ). In addition, Python also provides built-in functions for calculating the sequence length and finding the maximum and minimum elements.

2.2.1 Index

All elements in the sequence are numbered-starting from 0. These elements can be accessed by serial numbers:

>>> Greeting = 'hello'

>>> Greeting [0]

'H'

String Literal values (in this case, other serial literal values can also be used) can directly use indexes without a variable referencing them.

>>> 'Hello' [1]

'E'

If a function call returns a sequence, you can index the returned result directly.

>>> Fourth = raw_input ('year: ') [3]

Annual: 2025

>>> Fourth

'5'

Instance:

# Print the date in numbers based on the given year, month, and day

>>> Months = [

'January ',

'February ',

"March ",

'Cmdl ',

'May ',

'June ',

'July ',

'Audioest ',

'September ',

'October ',

'November ',

'December'

]

# List ending with a number ranging from 1 to 31

Endings = ['st', 'nd', 'rd'] + 17 * ['th'] \

+ ['St', 'nd', 'rd'] + 7 * ['th'] \

+ ['St']

Year = raw_input ('year :')

Month = raw_input ('month (1-12 :')

Day = raw_input ('day (1-31 ):')

Month_number = int (month)

Day_number = int (day)

# Subtract 1 from the month and number of days to obtain the correct index

Month_name = months [month_number-1]

Ordinal = day + endings [day_number-1]

Print month_name + ''+ ordinal +'' + year

Annual: 2015

Month (1-12:>? 5

Day (1-31):>? 13

May13th2015

2.2.2 multipart

Similar to using indexes to access a single element, you can use the sharding operation to access a certain range of elements.

>>> Tag = 'https: // d?qusza40orc.cloudfront.net/statistics'

>>> Tag [23: 37]

'Cloudfront. net'

Partition operations are useful for extracting part of a sequence. The serial number is particularly important here. The first index is the number of the 1st elements to be extracted, and the last index is the number of the remaining 1st elements after partitioning:

>>> Numbers = [1, 2, 4, 5, 6, 7, 8, 9]

>>> Numbers [3: 6]

[4, 5, 6]

In short, the implementation of the sharding operation requires two indexes as the boundary. The 1st indexes are contained in the shard, while the 2nd indexes are not included in the shard.

1. Elegant shortcuts

If you need to access the last three elements (based on the previous example), you can perform the following explicit operations:

If the part obtained contains the elements at the end of the sequence, you only need to leave the last index empty:

>>> Numbers [-3:]

[7, 8, 9]

This method also applies to elements starting with a sequence:

>>> Numbers [: 3]

[1, 2, 3]

2.3 list

2.3.1list Function

>>> List ('hello ')

['H', 'E', 'l', 'l', 'O']

2.3.2 basic list operations

1. Change the list: Element assignment

>>> X = [1, 1]

>>> X [1] = 2

>>> X

[1, 2, 1]

2. delete an element

>>> Names = ['Alice ', 'beth', 'cecil ', 'dee-dee', 'earl']

>>> Del names [2]

>>> Names

['Alice ', 'beth', 'dee-dee', 'earl']

3. multipart assignment

>>> Name = list ('perl ')

>>> Name

['P', 'E', 'R', 'L']

>>> Name [2:] = list ('ar ')

>>> Name

['P', 'E', 'A', 'R']

You can replace shards with sequences of different lengths from the original sequence:

>>> Name = list ('perl ')

>>> Name [1:] = list ('ython ')

>>> Name

['P', 'y', 't', 'h', 'O', 'n']

You can insert a new element without replacing any original element.

>>> Numbers = [1, 5]

>>> Numbers [1:1] = [2, 3, 4]

>>> Numbers

[1, 2, 3, 4, 5]

2.3 List Method

1. append

>>> Lst = [1, 2, 3]

>>> Lst. append (4)

>>> Lst

[1, 2, 3, 4]

2. count

>>> ['To', 'be', 'or', 'not', 'to', 'be']. count ('to ')

2

>>> X = [[], [, []

>>> X. count (1)

2

>>> X. count ([1, 2])

1

3. extend

>>> A = [1, 2, 3]

>>> B = [3, 4, 5]

>>> A. extend (B)

>>>

[1, 2, 3, 3, 4, 5]

>>> A = a + B has the same effect

4. index

>>> Knights = ['we', 'are ', 'the', 'knights ', 'who', 'Say ', 'ni']

>>> Knights. index ('who ')

4

>>> Knights [4]

'Who'

5. insect

>>> Numbers = [1, 2, 3, 5, 6, 7]

>>> Numbers. insert (3, 'four ')

>>> Numbers

[1, 2, 3, 'four ', 5, 6, 7]

6. pop

Removes an element from the list. The last element is used by default.

>>> X = [1, 2, 3]

>>> X. pop ()

3

>>> X

[1, 2]

7. remove

>>> X = ['to', 'be', 'or', 'not ', 'to', 'be']

>>> X. remove ('be ')

>>> X

['To', 'or', 'not ', 'to', 'be']

8. reverse

>>> X = [1, 2, 3]

>>> X. reverse ()

>>> X

[3, 2, 1]

9. sort

>>> X = [4, 5, 3, 1, 7]

>>> X. sort ()

>>> X

[1, 3, 4, 5, 7]

 

>>> X = [4, 5, 3, 1, 7]

>>> Y = x [:]

>>> Y. sort ()

>>> X

[4, 5, 3, 1, 7]

>>> Y

[1, 3, 4, 5, 7]

>>> Y = x. sort ()

>>> Print y

None

It should be:

>>> X = [4, 5, 3, 1, 7]

>>> Y = x [:]

>>> Y. sort ()

>>> X

[4, 5, 3, 1, 7]

>>> Y

[1, 3, 4, 5, 7]

Get a copy of the sorted list:

>>> X = [4, 5, 3, 1, 7]

>>> Y = sorted (x)

>>> X

[4, 5, 3, 1, 7]

>>> Y

[1, 3, 4, 5, 7]

10. advanced sorting

The compare (x. y) function returns a negative number when x <y, a positive number when x> y, and 0 if x = y.

>>> Cmp (40, 33)

1

>>> Cmp (33, 40)

-1

>>> Numbers = [5, 2, 9, 7]

>>> Numbers. sort (cmp)

>>> Numbers

[2, 5, 7, 9]

2.4 tuples: immutable Sequence

If you use commas to separate values, you will automatically create tuples.

>>> 1, 2, 3

(1, 2, 3)

>>> () # Empty tuples

()

2.4.1tuple Function

The functions of the tuple function are basically the same as those of the list function: Use a sequence as a parameter and convert it

 

Is a tuples.

>>> Tuple ([1, 2, 3])

(1, 2, 3)

>>> Tuple ('abc ')

('A', 'B', 'C ')

2.4.2 basic ancestor operations

Similar to the sequence

2.4.3 significance of tuples

Tuples can be used as keys in ing (and set members), while lists cannot exist as the return values of many built-in functions and methods. That is to say, you must process the tuples. As long as you do not try to modify the tuples, the "processing" tuples usually operate on them as lists (unless you need to use methods that are not available in tuples, such as index and count, the list may better meet all the requirements of the sequence.

Conclusion 2.5

Cmp (x, y) compares two values

Len (seq) returns the length of the sequence

List (seq) converts a sequence to a list.

Max (args) returns the maximum value in the sequence or parameter set.

Min (args) returns the minimum value in the sequence or parameter set.

Reversed (seq) performs reverse iteration on the sequence

Sorted (seq) returns a list of sorted elements including seq.

Tuple (seq) converts a sequence into a metagroup

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.