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)]

# 多个修改
list2[1:3] = ["hello world", "hello"] #
["hello world", "hello", [], (), 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


"""
列表的index方法,如果列表中有多个一样的元素,index方法是取出第一元素,如果我们想要取出后面的元素的下标
思路:可以先取出这个目标元素的第一个元素,然后index找出第一个元素的下标,然后从那里开始切片,切片之后找出目标元素的index
然后再两个下标相加
"""
lis = ["i", "hello world", [], (), "hello world", "welcome"]
first_hwd_index = lis.index("hello world")
print(lis[first_hwd_index]) # hello world
lis2 = lis[first_hwd_index:]
second_hwd_index = lis2.index("hello world")
second_hwd_index2 = first_hwd_index + second_hwd_index
print(lis[second_hwd_index2]) # hello world
 

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


lis = ["i", "hello world", [], (), "hello world", "welcome"]
# 判断某个元素是否在这个列表中
coun = lis.count("x")
print(coun) # 0 0表示lis中没有"x"这个元素
print("x" in lis) # False 表示没有这个元素
# 判断lis是否是一个list
print(type(lis) is list) # True

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
lis = [1, 2, 3, 4, 5]
del lis[2]
print(lis)     # [1, 2, 4, 5]

del lis
print(lis)     # NameError: name 'lis' is not defined  这个删除操作,将lis这个列表从内存中删除了

清空clear

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

7.排序

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,和列表一样
因为元组是不可变的元素集合,那么它就没有索引和切片

原文地址:https://www.cnblogs.com/zgzeng/p/11924928.html