列表
定义
由一系列按特定顺序排列的元素组成。索引从0开始而不是1开始。
bicycles=['trek','cannondale','spaciallized']
print(bicycles)
基本操作(修改列表)
在列表尾部增加元素
append()
bicycles.append('ducati')
print(bicycles)
在列表中插入元素
bicycles.insert(0,'ducati')
#在索引0处位置添加新元素
从列表中删除元素(del pop() remove)
del bicycles[0]
#删除列表中第一个元素
first_owned=bicycles.pop(0)
print('the first bicycle was a'+first_owned.title()+".")
#弹出元素,被弹出元素不在列表中
bicycles.remove('ducati')
#从列表中移除元素,可以继续使用该值
组织列表
bicycles=['trek','cannondale','spaciallized']
bicycles.sort()
print(bicycles)
#对列表进行永久性排序
bicycle.sort(reverse=True)
print(bicycles)
#对列表进行临时排序
print("here is the original list:"
print(bicycles)
print("\nhere is the sorted list:"
print(sorted(bicycles))
确定列表的长度
len(cars)
创建数值列表
for value in range(1:5):
print(value)
#遍历列表
nums=list(range(1:5))
print(nums)
nums=list(range(1:5))
print(num[0;2])
#切片
复制列表
my_food=['rice','juice']
frined_food=my_food[:]
元组
元组定义
元组看起来和列表很像,但使用圆括号()而不是【】来标识
列表用于存储可变化的数据集,列表是可以修改的,而元组不可修改。
nums=(1,2)
print(nums[1])
修改元组变量
虽然不能修改元组的元素,但是可以给存储元组的变量赋值,重新定义整个元组。
nums=(1,2)
nums=(2,5)
字符串
字符串定义
"this is a string."
修改大小写title()
upper()
lower()
name="lai fei"
print(name.title())
合并字符串
first_name="lai"
last_name="fei"
full_name=first_name+" "+last_name
print("hello,"+full_name.title()+"!")
字符串格式化
msg='''
---------- info of %s--------------
name=%s
age=%d
--------------end-------------------
'''%(name,name,age)
print(msg)