Handbook of Python3.5 cultivation 7

Source: Internet
Author: User

List


The list is different from the tuple and string: The contents of the list are variable (mutable).


the methods for updating a list are : element assignment, element deletion, shard assignment, and list method


Element Assignment Value

Marks an element of a particular location by number and re-assigns the element to that location

For example:

>>> a=[1,2,3,4,5,6]>>> a[1]=10>>> Print (a)

[1, 10, 3, 4, 5, 6]

>>> a[5]=88>>> Print (a)

[1, 10, 3, 4, 5, 6,88]

As you can see from the previous example, an element in the list is assigned according to the number

Here are the different types of assignments for the previous example

>>> #对编号4的元素赋一个字符串的值 >>> a[4]= ' Duyuheng ' >>> print (a)

[1, ten, 3, 4, ' Duyuheng ', 88]

>>> #查看赋值函数类型 ... type (a[5]) <class ' int ' >>>> type (a[4])

<class ' str ' >

As you can see from the type of the assignment function, the elements in a list can be assigned different types of values.

Be careful not to assign a value to the location of a nonexistent element

Can be used in conjunction with initialization in multiplication x null sequences

For example:

>>> tring=[none]*5>>> tring[4]= ' Duyuheng ' >>> print (tring)

[None, None, none, none, ' Duyuheng ']


add element Assignment

In Pyhon, you can add elements to the list, and using the Append () method, you can make the implementation

>>> list1=[1,2,3]>>> list1.append (4) >>> print (List1)

[1, 2, 3, 4]

Append () is a method for adding new objects at the end of a list.

Syntax List.append (obj)

The list represents the lists, and obj represents the objects that need to be added to the end of the list

Note: the append () method does not simply return a new list that has been modified, but instead modifies the original list directly.

The Append () method demonstrates:

>>> a=[1,2,3]>>> #添加字符串 ... a.append (' si ') >>> print (a)

[1, 2, 3, ' Si ']

>>> b=[' A ', ' B ', ' C ']>>> #添加数字 ... b.append (666) >>> print (b)

[' A ', ' B ', ' C ', 666]

Append () is the ability to add a string to a list of numbers, or to add a number to a sequence of strings.


Delete Element

You can add elements to the list, but you can also remove elements from the list.

For example:

>>> list2=[' A ', ' B ', ' C ', ' d ', ' E ']>>> del list2[3]>>> print (' after removing the 4th element: ', List2)

After deletion of the 4th element: [' A ', ' B ', ' C ', ' e ']

>>> Len (LIST2)

4

Del you can delete the characters in the list, or you can delete the numbers in the list.

For example:

>>> num=[10,20,30]>>> len (num)

3

>>> del num[2]>>> print (' delete 3rd element: ', num ') >>> len (num)

2


Shard Assignment

Shard Assignment is a powerful feature of the list.

Use the list () function to convert a string directly to a list.

For example:

>>> list (' I Love you Beautiful Girl ') [' I ', ' love ', ' You ', ' Beauty ', ' Li ', ' the ', ' gu ', ' Niang ']>>> boil=list (' I Love you Beautiful Girl ') >>> Print (boil)

[' I ', ' love ', ' You ', ' Beauty ', ' Li ', ' ', ' gu ', ' Niang ']

You can make changes directly to the list by assigning a value to the Shard.

For example:

>>> show=list (' Hi,boy ') >>> print (show)

[' H ', ' I ', ', ', ' B ', ' o ', ' y ']

>>> show[3:]=list (' man ') >>> print (show)

[' H ', ' I ', ', ', ' m ', ' a ', ' n ']

As you can see from the example, the Shard changes the element after the number 3 and replaces the boy with the man.

You can also replace shards with sequences that are not equal to the original sequence

>>> greeting=list (' Hi ') >>> print (greeting)

[' H ', ' I ']

>>> greeting[1:] =list (' ello ') >>> print (greeting)

[' H ', ' e ', ' l ', ' l ', ' O ']

You can also insert new elements at any location without replacing any elements.

For example:

>>> love=list (' I Love you Beautiful Girl ') >>> print

[' I ', ' love ', ' You ', ' Beauty ', ' Li ', ' ', ' gu ', ' Niang ']

>>> love[1:1]=list (' no ') >>> print (Love)

[' I ', ' No ', ' love ', ' You ', ' Beauty ', ' Li ', ' ', ' gu ', ' Niang ']

It is also possible to delete an element through a shard assignment

For example:

>>> love=list (' I Love you Beautiful Girl ') >>> print

[' I ', ' love ', ' You ', ' Beauty ', ' Li ', ' ', ' gu ', ' Niang ']

>>> love[3:6]=[]>>> print (Love)

[' I ', ' love ', ' You ', ' gu ', ' Niang ']

The functionality of the Shard delete is the same as the result of the Del delete operation


Nested lists

You can nest lists in a list, and the list of sets is taken out of the list.

For example:

>>> field=[' A ', ' B ', ' C ']>>> print (field)

[' A ', ' B ', ' C ']

>>> num=[1,2,3]>>> print (num)

[1, 2, 3]

>>> mix=[field,num]>>> Print (Mix)

[[' A ', ' B ', ' C '], [1, 2, 3]

>>> Mix[0]

[' A ', ' B ', ' C ']

>>> Mix[1]

[1, 2, 3]


List method

A method is a function that is closely related to an object, which may be a list, a number, or a string or other type of object.

Call syntax: Object. Method (Parameter)


Count

The count () method counts the number of occurrences of an element in the list.

Syntax for the Count () method:

List.count (obj)

The list represents the lists, and obj represents the objects that are counted in the list.

The Count () method demonstrates:

# (after the use of Pycharm knock code, CMD inside knocked too tired!!!) )

Field=list (' Hello.world ') print (field)

C:\python\python.exe c:/python.py/liebiaofangfa.py

[' H ', ' e ', ' l ', ' l ', ' o ', '. ', ' w ', ' O ', ' R ', ' K ', ' d ']

Print (' list field, number of letters O: ', Field.count (' O '))

C:\python\python.exe c:/python.py/liebiaofangfa.py

[' H ', ' e ', ' l ', ' l ', ' o ', '. ', ' w ', ' O ', ' R ', ' K ', ' d ']

List field, number of letters O: 2

Print (' list field, number of letters L: ', Field.count (' l '))

C:\python\python.exe c:/python.py/liebiaofangfa.py

List field, number of letters L: 3

Print (' list field, number of letters A: ', Field.count (' a '))

C:\python\python.exe c:/python.py/liebiaofangfa.py

List field, number of letters a: 0

listobj=[123, ' hello ', ' world ', 123]listobj=[26, ' Hello ', ' World ', 26]print (' Number of Numbers 26: ', Listobj.count (26))

C:\python\python.exe c:/python.py/liebiaofangfa.py

Number of digits 26:2

#统计字符串的个数print (' Hello number: ', listobj.count (' Hello '))

Hello Number: 1

You can also use this

Print ([' A ', ' B ', ' C ', ' A ', ' e ', ' f ', ' a '].count (' a '))

C:\python\python.exe c:/python.py/liebiaofangfa.py

3

You can also use this

Mix=[[1,3],5,6,[1,3],2]print (the number of lists [1,3] in a nested list is: ', Mix.count ([1,3]))

C:\python\python.exe c:/python.py/liebiaofangfa.py

The number of list [1,3] in the nested list is: 2


Extend

The Extend () method is used to append multiple values from another sequence at the end of the list (the original list is expanded with a new list)

The Extend () syntax is as follows;

List.extend (seq)

List represents lists, representing element lists

The Extend () method demonstrates:

a=[' Hello ', ' world ']b=[' python ', ' is ', ' Funny ']a.extend (b) print (a)

C:\python\python.exe c:/python.py/liebiaofangfa.py

[' Hello ', ' world ', ' python ', ' is ', ' funny ']

Make a comparison with the sequence addition

a=[' Hello ', ' world ']b=[' python ', ' is ', ' Funny ']print (a+b) print (a)

C:\python\python.exe c:/python.py/liebiaofangfa.py

[' Hello ', ' world ', ' python ', ' is ', ' funny ']

[' Hello ', ' world ']

The assignment of A and B in the two examples is the same, but the value of example 1 output A is different from the value of output a in Example 2

The main difference between the Extend () and the sequence addition is that the extend () method modifies the extended sequence, such as the previous A; the original join operation returns a completely new list, as the previous example returns a new list of copies that contain a and B, without modifying the original variable.

You can also use shard assignments to achieve the same results

a=[' Hello ', ' world ']b=[' python ', ' is ', ' Funny ']a[len (a):]=bprint (a)

C:\python\python.exe c:/python.py/liebiaofangfa.py

[' Hello ', ' world ', ' python ', ' is ', ' funny ']

The output is the same but no extend () method is easy to understand


Index

The index () method is used to find the index position of the first occurrence of a value from the list.

The index () syntax is as follows:

List.index (obj)

The list represents the listing, and obj represents the object being searched.

The index () method demonstrates:

name=[' Duyuheng ', ' Duzhaoli ', ' Xuwei ', ' Gaoshuang ', ' changting ']print (' Duyuheng ' index position: ', Name.index (' Duyuheng '))

C:\python\python.exe c:/python.py/liebiaofangfa.py

The index position of the Duyuheng is: 0

Print (' Xuwei index position: ', Name.index (' Xuwei '))

C:\python\python.exe c:/python.py/liebiaofangfa.py

The index position of the Xuwei is: 2

Search for a string that does not exist

Print (' Chaiergou index position: ', Name.index (' Caiergou '))

C:\python\python.exe c:/python.py/liebiaofangfa.py

Traceback (most recent):

File "c:/python.py/liebiaofangfa.py", line 7, <module>

Print (' Chaiergou index position: ', Name.index (' Caiergou '))

ValueError: ' Caiergou ' isn't in list

Error: Not in list


Insert

The Insert () method is used to find the index position of the first occurrence of a value from the list.

The insert () syntax is as follows:

List.insert (Index,obj)

The list represents the index, which represents the position at which the object obj needs to be inserted, and obj represents the object to insert in the list.

The Insert () method demonstrates:

Num=[1,2,3]print (' num before insertion: ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

Num before inserting: [1, 2, 3]

Num.insert (2, ' Insert before 2, 3 before ') print (' num after insertion: ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

num after insertion: [1, 2, ' Insert before 2, 3 ', 3]

Insert () can also be implemented using the method of Sharding assignment

For example:

Num=[1,2,3]print (' num before insertion: ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

Num before inserting: [1, 2, 3]

num[2:2]=[' Insert before 2 after 3 ']print (' num after insertion: ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

num after insertion: [1, 2, ' Insert before 2 3 ', 3]

The result of the output is the same as the insert (), but no insert is easy to understand.


Pop

The Pop () method removes an element from the list (the default is the last element) and returns the value of the element.

The syntax for POP () is as follows:

List.pop (Obj=list[-1])

The list represents the listing, obj is the optional parameter, and List[-1] represents the object to remove the list element.

The Pop () method demonstrates:

field=[' Hello ', ' world ', ' python ', ' is ', ' funny '] #不传参数, remove the last element by default Field.pop () print (' field after removing the element: ', field) # Remove the element numbered 3 Isfield.pop (3) Print (' field after removing the element: ', field)

C:\python\python.exe c:/python.py/liebiaofangfa.py

field after removing the element: [' Hello ', ' world ', ' python ', ' is ']

field after removing the element: [' Hello ', ' world ', ' python ']

The Pop () method is the only list method that can modify the list and return the element value (except none).

The method of using pop can implement a common data structure--stack

The principle of the stack, the last to be put into the stack is first removed, known as LIFO (in the first out), that is, FIFO.

The put and remove operations in the stack have a uniform title--into the stack (push) and the stack (POP).

Python does not have a stack method and can be replaced with the Append method.

The action of the pop method and the Append method is exactly the opposite.

If the stack (or append) is just the value of the stack, the final result will not change.

For example:

num=[1,2,3] #追加默认出栈的值num. Append (Num.pop ()) print (' num append default out-of-stack value operation result ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

num append default stack value operation result [1, 2, 3]

By appending the default out of the stack the list is the same as it was originally.


Remove

The Remove () method is used to remove the first occurrence of a value in the list.

The Remove () syntax is as follows:

List.remove (obj)

The list represents the listing, and obj is the object to remove in the list.

The Remove () method demonstrates:

field=[' I love ', ' beautiful ', ' Girl ']print (' Remove Pre-list field: ', field ')

C:\python\python.exe c:/python.py/liebiaofangfa.py

Remove previous list field [' I love ', ' beautiful ', ' girl ']

Field.remove (' beautiful ') print (' After removing the list field: ', field)

C:\python\python.exe c:/python.py/liebiaofangfa.py

After removing the list field: [' I love ', ' Girl ']

#移除一个不存在的值field. Remove (' chicken sister ') print (' After removing the list field: ', field)

C:\python\python.exe c:/python.py/liebiaofangfa.py

Traceback (most recent):

File "c:/python.py/liebiaofangfa.py", line 8, <module>

Field.remove (' chicken sister ')

ValueError:list.remove (x): X not in List

Error: Not in list

Note: Remove is a change method for the original location element without a return value, which modifies the list to have no return value, as opposed to the pop method.


Reverse

The reverse () method is used to reverse the elements in the list

The syntax for reverse () is as follows:

List.reverse ()

The list represents a listing, and the method does not require incoming parameters.

The reverse () method demonstrates:

Num=[1,2,3]print (num before ' list reversal: ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

Num before list reversal: [1, 2, 3]

Num.reverse () print (' num after list reversal: ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

Num after list reversal: [3, 2, 1]

The method changes the list but does not return a value (as with the previous remove).

If you need to reverse iterate over a sequence, you can use the reverse function.

Instead of returning a list, this function returns an iterator (Iterator) object that can be converted to a list by using the list function.

For example:

Num=[1,2,3]print (' Flip result with reversed function: ', list (reversed (num)))

C:\python\python.exe c:/python.py/liebiaofangfa.py

Flipping results using the reversed function: [3, 2, 1]

The output results in a reverse iteration of the original sequence.


Sort

Sort () sorts the original sequence table, and if the parameter is specified, it is sorted using the comparison method specified by the parameter.

The sort () syntax is as follows:

List.sort (func)

The list represents a listing, and Func is an optional parameter. If this parameter is specified, the method of the parameter is used to sort.

The sort () method demonstrates:

Num=[2,5,1,4,7]num.sort () print (' num ' after calling the sort method: ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

Num calls the Sort method after: [1, 2, 4, 5, 7]

The Sort method changes the original list instead of simply returning a sorted copy of the list.

How to do this if the user needs a sorted copy of the list while keeping the original list intact.

The way to do this is to assign the copy of Num to n first, and then sort n as follows

num=[2,5,1,4,7] #将列表切片后赋值给nn =num[:]n.sort () print (' The result of variable n is ', n ') print (' num's result is ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

The result of the variable n is [1, 2, 4, 5, 7]

The result of Num is [2, 5, 1, 4, 7]

Be sure to shard the original sequence when doing this, and don't let the two list point to the same list or two sequences will be sorted.

The sort method has a function of the same function ——— sorted function, which can directly get the list copy to sort

For example:

num=[2,5,1,4,7]n=sorted (num) print (' The result of variable n is ', n ') print (' num's result is ', num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

The result of the variable n is [1, 2, 4, 5, 7]

The result of Num is [2, 5, 1, 4, 7]

The sorted function can be used with any sequence, and the returned result is a list.

For example:

Print (sorted (' Python ')) print (sorted (' 31745 '))

C:\python\python.exe c:/python.py/liebiaofangfa.py

[' H ', ' n ', ' o ', ' P ', ' t ', ' Y ']

[' 1 ', ' 3 ', ' 4 ', ' 5 ', ' 7 ']


Clear

The clear () method is used to empty the list, similar to Del [a:].

The clear () syntax is as follows:

List.clear ()

List stands for lists, no incoming parameters required

The Clear () method demonstrates:

name=[' Duyuheng ', ' Duzhaoli ', ' Gaoshuang ', ' Xuwei ']name.clear () print (' name results after calling the Clear method: ', name ')

C:\python\python.exe c:/python.py/liebiaofangfa.py

Name results after calling the Clear method: []


Copy

The copy () method is used to copy the list, similar to a[:].

The copy () syntax is as follows:

List.copy ()

The list represents the lists and does not require incoming parameters.

The copy () method demonstrates:

name1=[' Duyuheng ', ' Duzhaoli ', ' Gaoshuang ', ' Xuwei ']name2=name1.copy () print (' name2 copy results: ', name2)

C:\python\python.exe c:/python.py/liebiaofangfa.py

name2 copy results: [' Duyuheng ', ' Duzhaoli ', ' Gaoshuang ', ' Xuwei ']


Advanced sorting

You can customize the comparison method if you want the elements to be sorted in a specific way (instead of using the Sort method by default in ascending order of the elements).

The sort method has two optional parameters, key and reverse. To use them is to specify by name, which we call the keyword argument.

Example:

field = [' study ', ' Python ', ' is ', ' happy '] #按字符串由短到长排序field. Sort (key=len) print (field)

C:\python\python.exe c:/python.py/liebiaofangfa.py

[' Is ', ' study ', ' Happy ', ' python ']

#按字符串由长到短排序, you need to pass two parameters

Field.sort (key=len,reverse=true) print (field)

C:\python\python.exe c:/python.py/liebiaofangfa.py

[' Python ', ' study ', ' Happy ', ' is ']

Can do sort after reverse order

For example:

Num=[8,6,1,4,5]num.sort (reverse=true) print (num)

C:\python\python.exe c:/python.py/liebiaofangfa.py

[8, 6, 5, 4, 1]



This article from "Duyuheng" blog, declined reprint!

Handbook of Python3.5 cultivation 7

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.