A list of built-in method

A list of built-in method

1. The value of the index, the index modification value

lt = [1,2,3,4]
print(lt[1])
lt[1] = 3
print(lt)

2
[1, 3, 3, 4]

2. Slice

print(lt[:])#冒号左边没有左边取到头,右边没有则右边取到头
print(lt[1:2])#顾头不顾尾,只打印索引号为1的元素
print(lt[1:4:2])#步长为2

[1, 3, 3, 4]
[3]
[3, 4]

3.for cycle

for i in lt:
    print(i**2)#打印列表每一个值的幂

1
9
9
16

4. The members of the operation

print(1 in lt)
print(5 in lt)

True
False

5.append()

lt.append(5)#往列表的最后一位添加元素
print(lt)

[1, 3, 3, 4, 5]

6.len

print(len(lt))

5

7.del Delete (delete the specified index number of the element)

print(lt)
del lt[0]
print(lt)

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

8.insert

lt=[1,2,3,4,5]
lt.insert(0,0)#向前插入
print(lt)

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

9.pop deleted in accordance with the index value

lt = [11,22,33,44,55]
lt.pop(0)
print(lt)

[22, 33, 44, 55]

10.remove delete the value by value

lt.remove(22)
print(lt)

[33, 44, 55]

11.count count

lt = [11,11,11,22]
print(lt.count(11))

3

12.index looking index values

print(lt.index(11))#找到了就返回

0

13.clear Clear List

lt = [1,2,3,4,5]
lt.clear()
print(lt)

[]

14.copy copy list

lt = [1,2,3,4]
lt1 = lt.copy()
print(lt1)

[1, 2, 3, 4]

15.extend extended list

lt1 = [1,2,3]
lt2 = [4,5,6]
lt1.extend(lt2)
print(lt1)

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

16.reverse () reverse list

lt = [1,2,3,4]
lt.reverse()
print(lt)

[4, 3, 2, 1]

Sort 17.sort

sort () function is used to sort the list of the original, if the parameter is specified using the comparison function specified comparison function.

grammar

sort () method syntax:

list.sort(cmp=None, key=None, reverse=False)

parameter

  • cmp - optional parameter, if this parameter is a method of using the parameter designated for sorting.
  • key - is mainly used for the comparison element, only one parameter, the specific parameter is a function of iteration may be taken from the object, specify one of the elements in the iteration to be sorted.
  • reverse - collation, Reverse = True descending, Reverse = False ascending (default).
lt = [2,3,1,0,4]
lt.sort(reverse=True)
print(lt)

[4, 3, 2, 1, 0]

Ordered or disordered: Ordered

Variable or immutable: variable

Bubble sort

for i in range(len(lt)):
    for j in range(len(lt)):
        if lt[i]<lt[j]:
            lt[i],lt[j] = lt[j],lt[i]
print(lt)

[0, 1, 2, 3, 4]

Guess you like

Origin www.cnblogs.com/ghylpb/p/11514990.html