#list列表操作
def testList():
#定义一个空列表
strList=[]
#新增
strList.append("a")
strList.append("b")
strList.append("1")
strList.append("2")
#循环
for item in strList:
print(item)
#或这么写循环
length=len(strList)
index=0
while index<length:
print(strList[index])
index+=1
#删除数组第二个元素
del strList[1]
for item in strList:
print(item)
#tuple元组元素不可以修改或删除
def testTuple():
# 定义一个tuple
my_tuple = (1, 2, 3, 4, 5)
# 使用for循环遍历tuple中的元素
for item in my_tuple:
print(item)
#元组和列表可以互转
my_list = list(my_tuple)
my_list[3] = 9
my_tuple = tuple(my_list)
#第4个元素被改成了9
for item in my_tuple:
print(item)
#dict字典操作
def testDict():
# 创建字典
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 访问字典元素
print(my_dict['name']) # 输出: Alice
print(my_dict.get('age')) # 输出: 25
# 添加或修改字典元素
my_dict['age'] = 26 # 修改
my_dict['job'] = 'Engineer' # 添加
# 删除字典元素
del my_dict['city'] # 删除键为'city'的条目
# 遍历字典
for key, value in my_dict.items():
print(key, value)
python学习(五):数据类型list列表,tuple元组,dict字典的使用
最新推荐文章于 2024-05-30 14:37:11 发布