Python Lessons The second week built-in data structures-lists and tuples

Source: Internet
Author: User

5 built-in data structures: lists, tuples, dictionaries, collections, strings. Three kinds of lists, dictionaries, and strings are called linear structures.

    • The operations for a linear structure are: slices, packets and packages, member operators, iterations.

    • There are analytic expressions for data structures: parsing is divided into List parsing, generator parsing, set parsing and dictionary parsing.

The following three species are peculiar to python3.x.

The basic framework is as follows:

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/8B/7C/wKiom1hPZYyjPAdMAABQd-R_pqE050.png "title=" Clipboard.png "style=" float:left; "alt=" Wkiom1hpzyyjpadmaabqd-r_pqe050.png "/>

List: The most flexible, ordered collection object type in Python

A list can contain objects of any kind: numbers, strings, dictionaries, collections, and even other lists, a feature called heterogeneous. Also has variable length and arbitrary nesting properties, which are variable length sequences.

(1) List initialization, There are two ways, the first use of the list () function, the second direct use of empty list assignment:

>>>lst=list () >>>lst=[1,2,3]

(2) Access to list elements, mainly through the subscript and index of the list. The subscript of the element starts at 0. If the given subscript exceeds the subscript range, a indexerror error is given. Also supports reverse access to the internal elements of the list, with the subscript starting from 1, while supporting the sequence of shard operations.

>>>lst[0] access to the first element 1>>>lst[-1] access to the last element, reverse access 3>>>lst[2] access to the last element 3>>>lst[ 0:] Access first to last element [three-to-one]

(3) How to list:

Increase

Append (object) #给列表添加一个对象object, the return value is None

Insert (Index,object) #给列表添加一个对象object, but you can determine the insertion position based on index, the return value of None

Extend (iterable) #从迭代器中添加元素到列表中

Here are a few examples:

LST=[5,2,10]

The index is within the list index range and is inserted normally:

>>>lst.insert (0,7) >>>lst[7,5,2,10]

The index exceeds the range of the list, in the last insert:

>>>lst.insert (100,13) >>>lst[7,5,2,10,13]

The index uses a negative value and is inserted in the normal index range from backward to forward:

>>>lst.insert ( -1,12) >>>lst[7,5,2,10,12,13]

The index uses a negative value but goes beyond the index range, inserting from the beginning:

>>> Lst.insert ( -100,20) >>> lst[20, 7, 5.2, 10, 12, 13]

To add an element from an iterator

>>>lst.extend ([5.2]) >>>lst[20, 7,, 10, 12, 13,1,2,3]

By deleting

The POP (index) #根据索引index将列表中的某个元素移除并返回这个元素, if no index is given, returns the last element. If the list is empty or the index is out of range, a indexerror error is given.

Lst=[5,2,10]>>>lst.pop () 10>>lst[5,2]>>>lst.pop (0) 5>>>lst[2]>>> Lst.pop ( -1) 2>>>lst[]

Remove (value) #根据value值删除list中的一个元素value, if value does not exist, will prompt ValueError, return value None

>>>lst=[5,2,10]>>>lst.remove[10]>>>lst[5,2]

Clear () #清除list中所有的元素, return value none.

>>>lst.clear () >>>lst[]

Del L[k]

Del L[i:j] Deletes a specified value based on an index or deletes a range of values

>>> lst=[1,2,3,4,5,6]>>> del lst[2]>>> lst[1, 2, 4, 5, 6]>>> del lst[0:2]>> > Lst[4, 5, 6]

Change

Reverse () #将list中的元素反转

Sort (Key=none, reverse=false) #将list中的元素有序排列, when reverse is true, the list is sorted in reverse order, and key is a function object that uses the function to sort the list. Returns none after sorting.

L[k] = n #根据列表索引来修改对应位置的值

Examples are as follows:

>>>lst= [5, 2, 10]>>>sort (LST) #排序 >>>lst[2,5,10]>>>reverse (LST) #倒转 >>> LST[10,5,2]>>>LST[0] = 100# index change >>>lst[100, 2, 10]

Check

Index (Value,[start,[stop]]) #根据value值, returns the index of value for the first time in the start and stop index ranges, and returns ValueError if value does not exist.

>>>lst= [' A ', ' B ', ' C ', ' d ', ' E ']>>>lst.index (' a ') 0>>>lst.append (' B ') >>> Lst.index (' B ', 0,4) 1

Count (value) #根据value值返回列表中value的个数, the return value is an integer

>>>lst.count (' B ') 2

Len (object,/) #返回列表中的元素个数

>>>len (LST) 6

Other methods

Copy () #返回list的一个副本.


Slicing operations

Basic format: Seq[start:stop:step], the output is [start,stop], step refers to the number of points to take a value, see the following example.

>>>lst=[1,2,3,4,5,6,7,8]>>>lst[0:8][1,2,3,4,5,6,7,8]>>>lst[0:8:2][1,3,5,7]

Because the slice operation is normally from left to right, start must be smaller than stop, otherwise you can only get an empty array.

>>>lst[7:5][]

In special cases, such as step<0, for example:

When Start>stop, Step=-1, Output (Stop,start]

>>>lst[5:1:-1][6,5,4,3]

When start or stop exceeds the index range (step>0), it is divided into 4 cases:

1. Start goes out of index, stop does not exceed index, and the absolute value of start is greater than the list length, output from index 0 to index Stop-1

>>>lst=[1,2,3,4,5,6,7,8] #列表长度为8 >>>lst[-10:5][1,2,3,4,5]

2. Start exceeds the index, stop does not exceed the index, and when the absolute value of start is less than the list length, the value range is [Len (LST) +start, stop]

>>>lst[-5:5] #取值范围是 [8-5,5], i.e. [3,5][4,5]

2. Stop exceeds index, start does not exceed index from start output until the last element stops

>>>lst[3,100][4,5,6,7,8]

3. When start and stop exceed the index at the same time, the start absolute value is greater than the array length, and the output SEQ first to the last element.

>>> lst[-100:100][1, 2, 3, 4, 5, 6, 7, 8]

4. When start and stop exceed the index at the same time, the value range is [Len (LST) +start:] When the start absolute value is less than the array length.

>>>lst[-5:100][4,5,6,7,8]


The slice operation supports omitting start or stop:

When start is omitted, output starts at index 0, to Stop-1 stop

>>>lst[:5][1,2,3,4]

When stop is omitted, starts from start and stops at the last element

>>>lst[3:][4,5,6,7,8]

When start and stop are omitted, all elements of the output seq.

Lst[:][1, 2, 3, 4, 5, 6, 7, 8]


Tuple (tuple): A collection of immutable data structures, an ordered set of objects.

Usually written as a series of items in parentheses, although tuples do not support any method calls, they have most of the properties of the list.

    • Through offset and indexed access

    • belongs to the type of the

    • Fixed length, not elongate or shortened, heterogeneous, can contain other composite objects, support nesting.

    • An array of object references, which is relatively quick to index the tuple.

1. Definition of a tuple

t= () #空元组t =tuple () #空元组t = (three-way) #3个元素的元组, the index can only be used to access the element t= (1,) #定义单个元素的元组时, you need to add a comma after the element, or T is a number.


2. Tuple methods

T.count (value) #返回元组内某个元素个数t. Index (Value,[start,[stop]) #返回元素value第一次出现的索引t [i], t[i:j] #根据索引来访问元素, the element t1+t2, T * 3 is accessed according to the Shard and length #合并和重复

* tuples are immutable only one layer , that is, when the elements of a tuple are single-layer or immutable elements, such as numbers, characters, tuple elements are immutable, but the elements of the tuple are multi-layered variable elements, the element itself cannot be changed, and the element intrinsic value is variable, such as the list, see example below:

1. When tuple elements are numbers and strings

>>>t = (1, ' Test ', 4) >>> t[0] = ' A ' Traceback (most recent call last): File "<stdin>", Line 1, in &  Lt;module>typeerror: ' Tuple ' object does not support item assignment #元素不可变 >>> t[1] = ' TEST ' Traceback (most Recent call last): File "<stdin>", line 1, in <module>typeerror: ' Tuple ' object does not support item Assignme NT #元素不可变

2. When a tuple element is a number, a list

>>>t = (1, [2, 3], 4) >>> t[1] = [4, 5]traceback (most recent The last): File ' <stdin> ', line 1, in <module>typeerror: ' Tuple ' object does not support item assignment #元组元素不可变 >>> t[1][1] = 5>>> t (1, [2, 5], 4) #列表仍然可变

Tuples are typically used to handle situations that have a fixed relationship and are applied in situations where immutable content is required.


This week's main points of knowledge are as follows:

    1. List initialization, basic additions and deletions to the method;

    2. Shard Processing for lists

    3. Initialization and basic methods of tuples


This article is from the "No Flying World" blog, please be sure to keep this source http://hf1208.blog.51cto.com/8957433/1882212

Python Lessons The second week built-in data structures-lists and tuples

Related Article

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.