Python--list Learning

Source: Internet
Author: User
Tags sorts

1. Introduction

In Python, list is called a listing, similar to a collection in Java, is a mutable array container, but the list in Python does not need to be declared in advance, you can store values that are not of the same data type, or you can make list nesting lists.

Create a list by enclosing separate data items separated by commas in square brackets. As shown below

List1=list () #利用list () The factory function creates an empty list
list2=['a','b','C',' D','e'] #创建一个字符列表
list3=[0,1,2,3,4] #创建一个整数列表
List4=[' A ', and, ' B '] #创建一个有字符有整数的列表
list5=[1,2,[3,4],[5,6],[7,[8,9]] #创建一个列表中包含列表, the type of value can also be inconsistent

Each element in the list is assigned an index (position), the first index is 0, the second index is 1, and so on.

When the index is negative, the index of the last element is-1. The index of the second penultimate element is-2, and so on.

We can use List_name[index] to remove elements from the list, such as list2[0],list3[1], corresponding to the character ' a ', 1. When our index was not present, an exception occurred (exception). For example output LIST3[5], there will be a Indexerror exception, because from the above we can see that this list3 list only 5 elements, his maximum index is 4, the index is 5 element does not exist.

2. MethodsIncrease:

List_name.insert (Index,obj) This method inserts an obj at the specified index position, with no return value, when the inserted position does not exist, negative numbers are inserted to the left of the negative index, and positive numbers are inserted at the tail

List_name.append (obj) This method inserts an obj at the trailing position, with no return value

list_name.extend (seq) This method expands the original list with a different sequence (list or tuple), with no return value 

>>>list1=[' A ', ' B ', ' C ', ' d '] #先创建一个list1列表
>>>list1.insert (0,'h') #在索引为0的位置插入 ' h ', no return value. When the insertion position is-1, it should be inserted at the left of the value ' d ' of the 1 index, and when the insertion position is 5, insert the trailer>>>List1 #打印出新的列表list1 ['h','a','b','C','D'] #结果显示
>>>list1.append (' g ') #在列表的尾部插入 ' G ', no return value
>>>list1 #打印出新的列表list1
[' H ', ' A ', ' B ', ' C ', ' d ', ' G ']#结果显示
>>>list1.extend ([up]) #在新列表扩充原有列表, no return value
>>>list1#打印出新的列表list1
[' H ', ' A ', ' B ', ' C ', ' d ', ' G ', up] #结果显示
By deleting:

Del List_name[index] This method removes the object from the specified index, no return value, and the object does not exist Indexerror

List_name.remove (obj) This method removes a specified object, no return value, and the object does not exist and is reported ValueError

List_name.pop (Index=-1) This method removes the object with the specified index, which defaults to 1, which is the trailing object, returns the object being removed, and the index does not exist to report indexerror.

>>>list1=['a','b','C','D','e']#Create a list of lists>>>list1.remove ('C')#Remove object ' C '>>>List1 ['a','b','D','e']>>>list1.pop ()#pops up the last element in the List1 list, which is ' E '    'e'>>>List1 ['a','b','D']>>>list1.pop (2)#pop-up element with index 2 in list1 list    'D'>>>List1 ['a','b']
Change:

For modifying the elements in the list, use the index of the list to find the element and assign the value directly

>>>list1=['a','b','C','D']#Create a list>>>list1[1]='Q'               #change the element with index 1 to ' Q '>>>List1 ['a','Q','C','D']
Check:

For elements in a lookup list, the element is found using the index of the list, or the first index position of obj appears using List_name.index (obj), and returns

>>>list1=[' A ', ' B ', ' C ', ' d ', ' B ']            #创建一个新列表 >>>list1[0]                             #查找索引为0的元素    ' a ' #输出结果
>>>list1.index (' B ') #输出 ' B ' first position appears
1
Other:

Sort: List_name.sort (Key=none,reverse=false)

Sorts the elements in the list without a return value, but changes its internal structure . There are 2 optional parameters, key specifies a function to sort by function, and the other is to specify whether descending is required. When the data types in the list are inconsistent, sorting in python3.x will throw typeerror,python2.x. If you do not want to change the internal structure of the original list, you need to use a list slice or use the sorted () function. (This does not describe the sort of objects, which are described later)

>>>list1=[' av ', ' ac ', ' Ada ', ' qwe ', ' rges ', ' sfgh ', ' Awewra ', ' Bnhjn '] #创建一个字符串列表 >>>list1.sort () #对 List1 is sorted and there are no return values, but the internal structure of the List1 list has changed since it was sorted, sorted by the value of the letters in the ASCII table >>>list1
[' AC ', ' Ada ', ' av ', ' Awewra ', ' bnhjn ', ' qwe ', ' rges ', ' sfgh ']>>>list1.sort (reverse=true) #此时用降序的结构对list1进行排序, Not a call is reversed once, but as soon as it becomes a sort by descending of the ASCII code table
[' Sfgh ', ' rges ', ' qwe ', ' bnhjn ', ' Awewra ', ' av ', ' ada ', ' AC '] #已经完成降序的排序, even if you call the previous statement more than once, the result is the same, no change occurs >>> List1.sort (Key=len) #通过函数进行排序, the function is length, that is, the length of each element is sorted by
[' AC ', ' av ', ' ada ', ' qwe ', ' rges ', ' sfgh ', ' bnhjn ', ' Awewra ']

# sort () This function will change the internal structure of the list, if we do not want to change the internal structure of the list, we need to use the slice or sorted () function.
>>>list2=[' a ', ' ab ', ' Ed ', ' cfs ', ' apk '
>>>list2[1:] #列表切片, copy a copy, copy is the original list index 1 start to end (including index 1)
[' Ab ', ' Ed ', ' cfs ', ' apk '] #这个为列表的切片副本, but no assigned name
>>>list3=list2[1:] #列表切片, copy a copy, copy is the original list index 1 start to end (including index 1), and assign this copy to the LIST3 list
>>>list3
[' Ab ', ' Ed ', ' cfs ', ' apk '] #生成了一个新的列表
>>>list4=list2[:3] #列表切片, copy a copy, copy the original list to the end of the index 3 (without index 3), and assign this copy to the List4 list
>>>list4
[' A ', ' ab ', ' Ed '] #生成了一个新的列表
>>>list5=list2[:] #列表切片, copy a copy, copy the same as the original list, and assign the copy to the LIST5 list
The difference between # # # slices and Direct Assignment # # #
>>>list1=[' a ', ' ab ', ' Ed '] #创建了一个列表对象 and generate a list1 tag pointing to this list object
>>>list2=list1[:] #拷贝了列表list1去生成一个新的列表对象, and then generate another label list2 to point to the list of the new copy, there are 2 tabs, and they point to their respective objects, although the elements inside the object are the same
>>>list3=list1 #生成一个list3标签, and this tab points to list1 this list object, so there are 2 tags, but only point to the same object, modified LIST1,LIST3 will change, and the slice will not
###

>>>list1=[' e ', ' a ', ' F ', ' C '] #创建一个新列表
>>>sorted (List1) #sorted () function returns a new list generated after the original list is sorted
[' A ', ' C ', ' e ', ' F ']
The >>>list2=sorted (list1) #通过sorted () function sorts the list1, the new list returned is assigned to the internal structure of the List2,list1 list, and the new List2 is the list1 sorted list
>>>list3=list1.sort () #这样赋值是错误的 because the sort () function does not return any values, so list3 is none because in Python, the function returns a none when it returns no value.

Reverse list: Lise_name.reverse () no return value, but the internal structure of the list has changed

Statistics element occurrences: List_name.count (obj) Number of times the statistic was returned

Maximum, Minimum: Max (list_name), Min (list_name) is not a list of the same type, whichever is maximum or minimum, throws TypeError

Convert a sequence to a list: list (seq)

Statistic list length: Len (list_name) returns the length of the list

Note: The contrast function cmp (LIST1,LIST2) has been removed in Python3 and can be used in Python2

3. Iteration

The usual iterations in the list are for loops, while loops are also available, but are seldom used.

>>>list1=[' A ', ' B ', ' C ', ' d ', ' e ']

>>>for each in List1:
   Print (each)

>>>count=0
>>>while Count<len (List1):
Print (List1[count])
   Count+=1

Python--list Learning

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.