Python新手入门之5大数据存储容器讲解

106 阅读8分钟

Python新手入门之5大数据存储容器讲解

1、字符串(str)

  1. 定义:字符串是一种不可变的序列,用于存储文本数据。字符串使用单引号 '' 或双引号 "" 定义。具有下标索引从0开始到(该字符串长度-1)为止。
str1='hello world'
str2="Welcome you coming"
#下标索引的输出
print(str1[1]) #结果为e
print(str2[0]) #结果为W
2. 字符串的方法(较多),介绍常见几种查找,替换,判断:count(),find(),replace(),startswith()...

(如果想了解更多方法可还请参照:https://www.runoob.com/python)

var = "hello and python and hello world"
print(var.find("and")) #返回结果为6,.find() :检测某个字符串是否包含在这个字符串中,如果在,返回这个字符串开始的位置下标,否则则返回-1。
print(var.count("and") #输出为2,.count()判断某个子串在字符串中出现的次数,
print(var.replace('and','or',2)) #输出结果为:hello or python or hello world ,所以.replace()用来替换换字串的内容。其中‘2’是替换的次数
print(var.startswith('hello')) #检查字符串是否以指定字串开头,输出结果为布尔型Ture,与之相反的是endswith():检查字符串是否以指定字串结尾
3.字符串运算
#1、字符串拼接
#用+拼接
var1="hello"+"word" #print(var1)输出的结果为helloword
#用.join
symbol = "-";
seq = ("a", "b", "c"); # 字符串序列
print(symbol.join(seq)) #输出结果为:a-b-c
#使用str.formate()
str1 = "Hello"
str2 = "World"
result = "{} {}".format(str1, str2)
print(result) #输出结果为Hello World

#2、字符串截取
#[:]
s = "Hello World!"
substring = s[start_index:end_index] #其中 `start_index` 是起始索引,`end_index` 是结束索引(不包含在截取的子串中)。例:print(s[0:5])的输出结果为Hello
print(s[2:8:2]) #[2:3:2]则其中第三个数为步长,输出结果为HloW
print(s[0:-1]) #-1表示最后一个元素,输出结果为Hello World
#.split()
s = "Hello, World!"
substrings = s.split(",")  # 使用逗号分割字符串,返回的是一个列表输出结果为["Hello"," World!"]
#**使用 `str.find()` 或 `str.index()` 方法:**(这两种方法可以用于查找子串的位置,然后提取子串。)
s = "Hello, World!"
index = s.find(",")  # 或者使用 s.index(",")
if index != -1:
    substring = s[:index] #输出结果为Hello
    
#3、in:成员运算符 - 如果字符串中包含给定的字符返回 True
var ="Welcome"
print('w' in var) #输出结果为True反之没有就为False
print('H' not in var) #输出结果为True反之没有就为False

#4、转义和取消转义
#转义
escaped_quote = "He said, \"Hello!\""
escaped_backslash = "This is a backslash: \\"
print(escaped_quote)
print(escaped_backslash) #上面字符中的“"\”表示一个“"”,而“\\”表示一个“\”
#取消转义
escaped_string = "This is a line break: \n Second line."
raw_string = r"This is a line break: \n Second line."
print(escaped_string)
print(raw_string) #讲这么多了应该可以自己尝试打印观察不同点了吧

#5、格式字符串
# % 操作字符格式话字符串,类似于c语言里的printf()函数
name = "Alice"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string)
# f-字符串
name = "Charlie"
age = 35
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string)
#str.format()方法
name = "Bob"
age = 25
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string)

2、列表(list)

1. 定义:列表是一种有序的可变容器,可以包含任意类型的元素。列表使用方括号 [] 定义,元素之间用逗号分隔:list1=[1,2,3,4,5] list2=['海底两万里','格兰特船长的儿女',"神秘岛"]。且同字符串一样也有索引 list1[0]=1。
2. 列表的操作:修改、添加、删除

#1、修改
my_list=[1,2,3]
my_list[1]=4 #print输出的结果:[1,4,3]

#2、添加
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # 输出: [1, 2, 3, 4]
my_list = [1, 2, 3]
my_list.insert(1, 5)  # 在索引 1 的位置插入元素 5
print(my_list)  # 输出: [1, 5, 2, 3]
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)  # 输出: [1, 2, 3, 4, 5, 6]

#3、删除
my_list = [1, 2, 3, 4, 3]
my_list.remove(3)  # 移除第一个值为 3 的元素
print(my_list)  # 输出: [1, 2, 4, 3]
my_list = [1, 2, 3, 4]
removed_element = my_list.pop(1)  # 移除索引 1 的元素,并返回被移除的值
print(my_list)  # 输出: [1, 3, 4]
print(removed_element)  # 输出: 2
my_list = [1, 2, 3, 4]
my_list.clear()
print(my_list)  # 输出: []

#4、切片赋值
my_list = [1, 2, 3, 4]
my_list[1:3] = [5, 6]  # 替换索引 1 到 2 的元素
print(my_list)  # 输出: [1, 5, 6, 4]
3、列表的遍历
#1、使用for循环
my_list = [1, 2, 3, 4, 5]
for item in my_list:
    print(item) #分别输出1,2,3,4,5  

#2、使用while循环
my_list = [1, 2, 3, 4, 5]
index = 0
while index < len(my_list):
    print(my_list[index])
    index += 1

#3、使用列表推导式
my_list = [1, 2, 3, 4, 5]
squared_list = [item for item in my_list]
print(squared_list)

#4、使用range函数
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)):
    print(f"Index {i}: {my_list[i]}") 

#5、使用enumerate()
my_list = [1, 2, 3, 4, 5]
for index, item in enumerate(my_list):
    print(f"Index {index}: {item}") #该函数同时返回索引和元素

3、元组(tuple)

1、定义:元组是一种有序的不可变容器,一旦创建,就不能修改。元组使用圆括号 () 定义,元素之间用逗号分隔。例: tuple1=(1,2,3,4) 2、元组的操作以及一常用些方法

#1、通过下标去访问元素
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0])  # 输出: 1

#2、切片
my_tuple = (1, 2, 3, 4, 5)
sliced_tuple = my_tuple[1:4]
print(sliced_tuple)  # 输出: (2, 3, 4)

#3、合并元组通过'+'
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
merged_tuple = tuple1 + tuple2
print(merged_tuple)  # 输出: (1, 2, 3, 4, 5, 6)

#.index(),count(),len()用法与列表和字符串的index相同
tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1.index('aa')) #输出结果为0
print(tuple1.count('bb')) #输出结果为2
print(len(tuple1)) #输出结果为4
3、元组遍历同列表类似

这里就介绍一个for其它想了解可关注up看后续发布的文章,就不详细说啦!

屏幕截图 2023-12-15 030103.png

4、集合(set)

1、定义:集合是一种无序的、唯一的容器,不能包含重复的元素。集合使用花括号 {} 定义,元素之间用逗号分隔。 例:my_set={1,2,3,4,5,6}
2、集合的特点:
  • 无序性: 集合中的元素没有固定的顺序,因此不能通过索引来访问或修改元素。集合中的元素是无序排列的,但是你可以将集合转换为列表然后再通过索引拿到想要的元素注意当转换为列表后元素的顺序可能会发生变化

屏幕截图 2023-12-15 031151.png

  • 唯一性: 集合中的元素是唯一的,不允许重复。如果尝试向集合中添加已存在的元素,集合会自动忽略该操作。
my_set = {1, 2, 3, 3, 4}
print(my_set)  # 输出: {1, 2, 3, 4}
  • 数学集合运算: 集合支持数学集合运算,如并集、交集、差集等。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2  # 并集用|或union 输出{1,2,3,4,5}
intersection_set = set1 & set2  # 交集用&或intersection 输出 {3}
difference_set = set1 - set2  # 差集用-或dirrerence 输出{1,2}
print(set1<set2) #子集用<或issubset 输出False
  • 可变性: 集合是可变的,可以通过添加、删除元素来修改集合。这与元组不同,元组是不可变的数据类型。
my_set = {1, 2, 3}
my_set.add(4)  # 添加元素
my_set.remove(2)  # 删除元素
print(my_set)  # 输出: {1, 3, 4}

5、字典(dict)

1、字典的定义: 字典是一种键值对的映射容器,用于存储和检索数据。字典使用花括号 {} 定义,每个键值对之间用冒号分隔,键和值之间用逗号分隔。例: my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
2、字典的遍历

在Python中,字典(Dictionary)可以使用多种方式进行遍历。以下是一些常见的字典遍历方法:

#遍历键
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for key in my_dict:
    print(key)
#遍历值
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for value in my_dict.values():
    print(value)
#遍历键值对
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for key, value in my_dict.items():
    print(f"{key}: {value}")
#通过键来遍历值
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
for key in my_dict:
    value = my_dict[key]
    print(f"{key}: {value}")
3、字典的特点
  • 键值对存储: 字典是由键值对构成的,每个键值对都表示一个映射关系。键(key)是唯一的,而值(value)可以是任意类型的对象。
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
  • 无序性: 字典中的元素没有固定的顺序,不像列表或元组那样可以通过索引来访问。在Python 3.7之后,字典开始保留插入顺序。
  • 可变性: 字典是可变的,可以通过添加、删除或修改键值对来改变字典的内容
my_dict['gender'] = 'Male'  # 添加新的键值对
del my_dict['age']  # 删除指定键值对
my_dict['city'] = 'San Francisco'  # 修改值
  • 唯一性: 字典中的键是唯一的,同一个字典中不能包含重复的键。如果使用相同的键插入多次,后面的值会覆盖前面的值。 屏幕截图 2023-12-15 035554.png
  • 动态性: 字典可以动态地改变大小,可以根据需要灵活地添加或删除键值对。 屏幕截图 2023-12-15 035728.png
  • 多数据类型: 字典的值可以是任意数据类型,包括数字、字符串、列表、元组、其他字典等。
my_dict = {'name': 'John', 'scores': [85, 90, 78], 'info': {'gender': 'Male', 'age': 25}}

总结:各个数据容器之间有不同的用法也有相同的用法我们在使用的同时,要按自己的需求去合理选择使用。如果以上有不足之处或者是要修改的地方可在评论区留下你的评论up会尽力去完善的!如果要更详细了解则可转至www.runoob.com/python 官方文档查看,最后,谢谢留言和阅读!