基本数据类型题目

1、列表的操作

  • 可变的数据类型,增删改查等操作都可以进行

1、案例1

  • fruits=['苹果', '香蕉', '橙子', '葡萄', '西瓜']

  • 向列表中添加两种新水果:'菠萝'和'芒果'

fruits=['苹果', '香蕉', '橙子', '葡萄', '西瓜']
fruits.extend(["菠萝","芒果"])
print(fruits)

# 输出结果

['苹果', '香蕉', '橙子', '葡萄', '西瓜', '菠萝', '芒果']

  • 从列表中删除'香蕉'元素
# 三个删除都可以

# fruits.remove("香蕉")
# fruits.pop(1)
del fruits[1]
  • 将列表中的'橙子'改为'柑橘'
fruits[2]="柑橘"
  • 检查'葡萄'是否在列表中,并返回其索引
l_num=fruits.index("葡")
print(l_num)
  • fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'],对这个列表进行统计
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
count={}
for i in fruits:
    # 字典赋值,值为数字,出现的次数+1
    count[i]=count.get(i,0)+1

print(count)

2、案例2

  • numbers = [10, 20, 30, 40, 50, 60]

  • 获取列表中的第2到第4个元素(包含第4个)

  • 对列表进行降序排序

numbers = [10, 20, 30, 40, 50, 60]
print(numbers[2:5])


numbers.sort(reverse=True)
print(numbers)

# 输出结果为
[60, 50, 40, 30, 20, 10]

2、元组

  • 创建一个包含4个元素的元组,并访问第二个元素,my_tuple = ('apple', 'banana', 'orange', 'grape')
my_tuple = ('apple', 'banana', 'orange', 'grape')
print(my_tuple[1])
  • 创建一个包含三个元素的元组,然后将其拆包到三个变量中
    my_tuple = ('John', 25, 'Engineer')
my_tuple = ('John', 25, 'Engineer')
a,b,c=my_tuple
print(a)
print(b)
print(c)
  • 创建两个元组,并将它们合并成一个新元组,tuple1 = (1, 2, 3),tuple2 = (4, 5, 6)
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
t3=tuple1+tuple2
print(t3)

# 输出结果为
(1, 2, 3, 4, 5, 6)

  • 检查元组中是否包含某个元素,my_tuple = (10, 20, 30, 40, 50),检查30是否在元组中
my_tuple = (10, 20, 30, 40, 50)
for i in my_tuple:
    if i == 30:
        print("yes")

  • 使用切片获取元组中的一部分,my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),获取第3到第7个元素
result = my_tuple[3:8]
print(result)

# 输出结果为
(4, 5, 6, 7, 8)

3、字典

  • 访问字典中的'age'键的值person = {'name': 'Bob', 'age': 25, 'city': 'London'},2种方法
person = {'name': 'Bob', 'age': 25, 'city': 'London'}
print(person["age"])
print(person.get("age"))
  • 向字典中添加一个新的键值对
person["save"]="10000"
# 2个方法都可以
person.update(save="10000")
  • 修改字典中'age'键的值
person["age"]=30

person.update(age=30)
  • 删除字典中的'city'键,2种方式
person.pop("age")
del person["age"]
  • 遍历字典
# 元组存储数据,不可变数据类型,但是可以使用索引
for i in person.items():
    print(i)

4、字符串

  • 将两个字符串拼接在一起,str1 = "Hello",str2 = "World"
str3 = str1+str2
  • 查找子字符串在字符串中的位置,text = "Python is a programming language"
s1=text.find("is")

# 输出的索引
7
  • 将字符串中的"Python"替换为"Java"
s1=text.replace("Python","Java")
print(s1)

# 输出结果为
Java is a programming language
  • text = "Python is a programming language",将字符串按空格分割成列表
s1=text.split(" ")
print(s1)

# 输出结果为
['Python', 'is', 'a', 'programming', 'language']
  • 按特定字符分割,csv_text = "apple,banana,orange,grape"
csv_text = "apple,banana,orange,grape"
s1=csv_text.split(",")
print(s1)

# 输出结果为
['apple', 'banana', 'orange', 'grape']
posted @ 2025-09-17 19:48  乔的港口  阅读(12)  评论(0)    收藏  举报