python基本数据类型之列表和元组

一.列表(list)

列表是有序的可变的元素集合 。像字符串值用引号来标记字符串的起止一样,列表用左方括号开始,右方括号结束, 即[]。列表中的值也称为“表项”。

二、创建列表的方法

方法1:list_name = [element1, element2, element3, element4......]

比如:

list_1 = [1, 3.14, (), [], True, {"k1":"v1"}, 1+2j]
print("list_1的数据类型是:", type(list_1))     # list_1的数据类型是: <class 'list'>

方法2:使用list()函数创建列表

tuple1 = (1, 3.14, [], (), True)
print("tuple的数据类型是:", type(tuple1))     # tuple的数据类型是: <class 'tuple'>
list2 = list(tuple1)
print("list2的数据类型是:", type(list2))      # list2的数据类型是: <class 'list'>

list中的元素可以是整型,浮点型,元组,列表,布尔值,复数, 字典等。

三、列表中常用的方法

根据列表的概念,它是一个可变有序的元素集合,那么它拥有增删改查的操作。

1、index索引

# index索引,和字符串的索引一样list_name[index]
list2 = [8, 3.14, [], (), True, {"k1":"v1"}, 1+2j]
a = list2[5]
print(a)  # {'k1': 'v1'}

2.切片

# 切片list_name[开始:结尾:[步长]]
b = list2[2:5]
print(b)           # [[], (), True]
c = list2[-5:-2]   
print(c)           # [[], (), True]

# 步长
list3 = list2[::2]    
print(list3)       # [8, [], True, (1+2j)] 

# 逆序
d = list2[5:2:-1]
print(d)           # [{'k1': 'v1'}, True, ()]
e = list2[-2:-5:-1]
print(e)           # [{'k1': 'v1'}, True, ()]

3.改

列表的修改,已经将原来的列表改变了

list2 = [8, 3.14, [], (), True, {"k1": "v1"}, 1+2j]
#
list2[2] = "hello world!"
print(list2)      # [8, 3.14, 'hello world!', (), True, {'k1': 'v1'}, (1+2j)]

 4.增

追加append

""" Append object to the end of the list. """
li = [1., 8, "hello world", 1+1j, [], (), {} ]
li.append("China")
print(li)         # [1.0, 8, 'hello world', (1+1j), [], (), {}, 'China']

批量追加 extend

""" Extend list by appending elements from the iterable. """
li.extend(["i", {1, 2, 44, 88}])
print(li)        # [1.0, 8, 'hello world', (1+1j), [], (), {}, 'China', 'i', {88, 1, 2, 44}]

定位增加insert

"""
    def insert(self, *args, **kwargs): # real signature unknown
        Insert object before index. 
"""
li.insert(4, "hello everybody!")
print(li)      # [1.0, 8, 'hello world', (1+1j), 'hello everybody!', [], (), {}, 'China', 'i', {88, 1, 2, 44}]

5. 查

index

"""
Return first index of value.

Raises ValueError if the value is not present.
"""

a = li.index(8) print(a) # 1 b = li.index("hello everybody!") print(b) # 4
c = li.index("hello girl") 
print(c) # ValueError: 'hello girl' is not in list
 

count

""" Return number of occurrences of value. """
li = [1.0, 8, 8, 8,  'hello world', (1+1j), 'hello everybody!', [], (), {}, 'China', 'i', {88, 1, 2, 44}]
d = li.count(8)    
print(d)         # 3
e = li.count("hello world!")
print(e)         # 0

6.删

单个删除 remove

"""
Remove first occurrence of value.

Raises ValueError if the value is not present.
"""
li.remove(8)
print(li)    # [1.0, 8, 8, 'hello world', (1+1j), 'hello everybody!', [], (), {}, 'China', 'i', {88, 1, 2, 44}]
li.append('hello world')
print(li)   #  # [1.0, 8, 8, 'hello world', (1+1j), 'hello everybody!', [], (), {}, 'China', 'i', {88, 1, 2, 44}, 'hello world']
li.remove('hello world')
print(li)   # [1.0, 8, 8, (1+1j), 'hello everybody!', [], (), {}, 'China', 'i', {88, 1, 2, 44}, 'hello world']
li.remove("hello girl")
print(li)   # ValueError: list.remove(x): x not in list

指定删除pop

"""
Remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
"""
print(li)   # [1.0, 8, 8, (1+1j), 'hello everybody!', [], (), {}, 'China', 'i', {88, 1, 2, 44}, 'hello world']
a = li.pop()
print(a)     # hello world
b = li.pop(8)
print(b)     # China
c = li.pop(88)
print(c)      # IndexError: pop index out of range

清空clear

""" Remove all items from list. """
li.clear()
print(li)    # []

6.排序

sort方法

list_1 = [2, 8, 3, 59, 10]
list_1.sort()
print(list_1)      # [2, 3, 8, 10, 59]

list_2 = [4, 57, 2, 85, 20, 33, 0]
list_2.sort(reverse=True)
print(list_2)     # [85, 57, 33, 20, 4, 2, 0]

reverse方法

这个方法是逆序,和list[::-1]一样的效果

list_3 = [23, 45, 13, 58, 29, 4]
list_3.reverse()
print(list_3)    # [4, 29, 58, 13, 45, 23]

四、元组

元组: 元组是有序的不可变的元素的集合

a = ()
b = (1, 1., False)
c = 1, 1., False
d = (1,) # 如果只有一个元素必须带上一个逗号,如果是d=(1),那么d的数据类型是int
e = (1)
print("d的数据类型是:", type(d))   # d的数据类型是: <class 'tuple'>
print("e的数据类型是:", type(e))   # e的数据类型是: <class 'int'>
功能

index 和count方法
len()
包含in,和列表一样
因为元组是不可变的元素集合,那么它就没有索引和切片

猜你喜欢

转载自www.cnblogs.com/zgzeng/p/11924928.html