2-python tuples and lists

table of Contents

Tuple

List

1, tuple

- ordered arrangement of elements

- a tuple of elements need not have the same type

- elements can not add, modify, and delete

1.1, create a tuple

# Create a tuple

tup1 = (1,2,3,4)

tup2 = tuple('a','b','c')

tup3 = "aa","bb","cc"

To create a comma when # tuple,

tup4 = (1)

# Create an empty tuple

tup5 = ()

tup6 = tuple()

1.2, visit tuple

- be accessed via the index tuples

a =  (1,2,3,4,5,6)

# Access positive sequence starting from 0

a[0]

>>1

a[3]

>>4

# Reverse order access starting at -1

a[-1]

>>6

# Access to multiple elements

a[1:4]

>>(2,3,4,5)

1.3, calculation tuple

TUP = (1,2,3,4,5,6)

# Tuple combination

a = (1,2,3)

b = (4,5,6)

a + b

>>(1,2,3,4,5,6)

# Tuple copy

a * 3

>>(1,2,3,1,2,3)

# Delete tuples

of the

a

>>

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

1.4, built-in functions tuple

TUP = (1,2,3,4,5)

# Yuan Group Length

wool (TUP)

>>5

The smallest element # tuple

min (tup)

>>1

# Tuple elements within a maximum

max(tup)

>>5

# Tuples into a sequence

tuple([1,2,3,4])

(1,2,3,4)

2. List

- ordered arrangement of elements

- a list of the elements need not have the same type

- 列表中的元素可以为:数字、元组、列表、字典、集合、字符串、布尔值等等

- 元素可以增删查改

2.1、创建列表

list1 = [1,2,3,'a']

# 创建空列表

list2 = []

list3 = list()

2.2、访问列表

- 通过下标访问列表

list = [1,2,3,4]

list[1]

>>2

# 倒序访问

list[-1]

>>4

# 切片访问

list[1:2]

>>[2,3]

list[1:]

>>[2,3,4]

2.3、修改列表

- 通过下标修改列表中的元素

list = [1,2,3]

list[1] = 'a'

list

>>[1,'a',3]

- 通过下标删除列表中的元素

list = [1,2,3]

del list[1]

list

>>[1,3]

2.4、列表运算

# 列表组合

a = [1,2,3]

b = [4,5,6]

a + b

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

# 元组复制

a * 3

>>[1,2,3,1,2,3]

# 删除列表

del a

a

>>

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'l' is not defined

2.5、列表函数

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

# 求列表长度

len(list)

>>5

# 求列表中值最大的元素

max(list)

>>5

# 求列表中值最小的元素

min(list)

>>1

# 将序列转为列表

a = 'asdaf'

list(a)

>>['a','s','d','a','f']

2.6、列表方法

注:加*为必传参数

- list.append(元素*)----------------------向列表末尾添加元素

- list.count(元素*)-------------------------统计某元素在列表中出现的次数

- list.extend(seq*)------------------------一次性在列表的末尾添加多个值

- list.index(元素*)------------------------从列表中找出某元素第一次匹配的索引

- list.insert(index*,元素*)----------------将某元素插入到列表中指定索引的位置,后面的元素索引依次后推一位

- list.pop(index)--------------------------删除指定索引位置的元素,并返回被删除的元素,不传index默认index=0

- list.remove(元素*)----------------------删除列表中的某元素的第一个匹配项

- list.reverse()----------------------------将列表倒序排列,并返回一个新的列表

- list.sort(key=None,reverse=False)------对原列表进行排序,reverse默认为False

- list.clear()--------------------------------清空列表

- list.copy()--------------------------------复制列表,返回复制后的新列表

Guess you like

Origin www.cnblogs.com/new-hashMap/p/12030817.html