List使用
支持中文设置 UTF8+BOM
代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# List的使用
class_mates = ['王林', '北京',"宏卫","华治"]
print("一共有 %d 个同学,分别为 %s " % (len(class_mates), class_mates))
运行结果
D:\PythonProject>python helloworld.py
一共有 4 个同学,分别为 ['王林', '北京', '宏卫', '华治']
上面有一个len()的方法,求长度的
List的增删改查
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# List的使用
class_mates = ['王林']
print("开始 %d 个同学Python, 分别为 %s " % (len(class_mates), class_mates))
# 追加一个同学
class_mates.append('北京')
print("现在 %d 个同学Python, 新同学 %s 是append进来的 " % (len(class_mates), class_mates[1]))
# 插入
class_mates.insert(1,"宏卫")
print("现在 %d 个同学Python, 新同学 %s 是insert进来的 " % (len(class_mates), class_mates[1]))
# 删除
# class_mates.pop(index)
# 可以是不同类型的变量
class_mates.append(123)
print("现在 %d 个同学Python, 新同学 %s 是append进来的 " % (len(class_mates), class_mates[3]))
# 修改
class_mates[3] = "华治"
print("现在 %d 个同学Python, 新同学 %s 刚刚修改名字 " % (len(class_mates), class_mates[3]))
print("现在 %d 个同学Python, 分别 %s" % (len(class_mates), class_mates))
运行结果
D:\PythonProject>python helloworld.py
开始 1 个同学Python, 分别为 ['王林']
现在 2 个同学Python, 新同学 北京 是append进来的
现在 3 个同学Python, 新同学 宏卫 是insert进来的
现在 4 个同学Python, 新同学 123 是append进来的
现在 4 个同学Python, 新同学 华治 刚刚修改名字
现在 4 个同学Python, 分别 ['王林', '宏卫', '北京', '华治']
让我最为佩服的是list可以放不同类型的变量,简直是跪了跪了
Tuple
这里我理解为java的数组
代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# tuple的使用
# List使用[]围起来,tuple使用()围起来
mTuple = ("王林","宏卫","北京","华治",[1,3])
print(mTuple)
mTuple[4][0] = 8
mTuple[4][1] = 8
print(mTuple)
运行结果
D:\PythonProject>python helloworld.py
('王林', '宏卫', '北京', '华治', [1, 3])
('王林', '宏卫', '北京', '华治', [8, 8])
写法区别
- mList = [item1, item2]
- mTuple = (item1, item2)