Files
2026-03-31 11:27:27 +08:00

44 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 用方括号创建列表,元素之间用逗号分隔
fruits = ['苹果', '香蕉', '橙子', '葡萄'] # 字符串列表
numbers = [1, 2, 3, 4, 5] # 整数列表
mixed = ['hello', 123, True, 3.14] # 混合列表
fruits = ['苹果', '香蕉', '橙子', '葡萄']
print(fruits[0]) # 第一个元素:苹果
print(fruits[1]) # 第二个元素:香蕉
print(fruits[-1]) # 最后一个元素:葡萄
print(fruits[-2]) # 倒数第二个:橙子
fruits = ['苹果', '香蕉', '橙子', '葡萄']
[0] [1] [2] [3]
[-4] [-3] [-2] [-1]
fruits = ['苹果', '香蕉', '橙子', '葡萄']
fruits[0] = '西瓜' # 修改第一个元素
print(fruits) # ['西瓜', '香蕉', '橙子', '葡萄']
fruits = ['苹果', '香蕉', '橙子', '葡萄']
fruits.append('草莓') # 在末尾添加
print(fruits) # ['苹果', '香蕉', '橙子', '葡萄', '草莓']
fruits.insert(1, '桃子') # 在索引1的位置插入
print(fruits) # ['苹果', '桃子', '香蕉', '橙子', '葡萄', '草莓']
fruits = ['苹果', '香蕉', '橙子', '葡萄']
fruits.remove('香蕉') # 删除指定元素(删除第一个匹配的)
print(fruits) # ['苹果', '橙子', '葡萄']
del fruits[0] # 删除指定索引的元素
print(fruits) # ['橙子', '葡萄']
fruits = ['苹果', '香蕉', '橙子', '葡萄']
print(len(fruits)) # 4
fruits = ['苹果', '香蕉', '橙子', '葡萄']
# 方法1直接遍历最常用
for fruit in fruits:
print(fruit)
# 方法2带索引遍历
for i, fruit in enumerate(fruits):
print(f'{i}: {fruit}')