1.List的使用
# This is my shopping list
# 列表是可变的(Mutable) 而字符串是不可变的(Immutable)
shoplist =
# 输出list的长度
print('I have ', len(shoplist), 'items to purchase')
# 输出items项
print('These items are:', end=' ')
for item in shoplist:
print(item, end=' ')
# 添加数据
print('\nI also have to buy rice.')
shoplist.append('rice')
print('My shopping list is now', shoplist)
# 排序list,按照首字母排序
print('I will sort my list now')
shoplist.sort()
print('Sorted shopping list is', shoplist)
# 取出第0个数据
print('The first item I will buy is', shoplist)
olditem = shoplist
# 删除第0个数据
del shoplist
print('I bought the', olditem)
# 输出当前的list数据
print('My shopping list is now', shoplist)2.Dic的使用
# “ab”是地址(Address) 簿(Book) 的缩写
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}
print("Swaroop's address is", ab)
# 删除一对键值—值配对
del ab
print('\nThere are {} contacts in the address-book\n'.format(len(ab)))
# 输出字典中的元素
for name, address in ab.items():
print('Contact {} at {}'.format(name, address))
# 添加一对键值—值配对
ab = 'guido@python.org'
ab = 'uestc@126.com'
# 寻找指定元素的值
if 'Guido' in ab:
print("\nGuido's address is", ab)3.Set的使用
# 简单对象的无序集合
bri = set()
print('india' in bri)
print('usa' in bri)
# 再次创建一个集合
bric = bri.copy()
print(bric)
# 集合添加元素
bric.add('China')
print(bric)
print(bric.issuperset(bri))
# 删除元素
bric.remove('China')
print(bric)
# 取出两个集合中的交集部分
print(bri & bric)4.Tuple的使用# 我会推荐你总是使用括号
# 来指明元组的开始与结束
# 尽管括号是一个可选选项。
# 明了胜过晦涩,显式优于隐式。
# 元组的初始化(包含项目的元组)
zoo = ('python', 'elephant', 'penguin')
# 输出元组的长度
print('Number of animals in the zoo is', len(zoo))
# 把两个元组拼接起来
new_zoo = 'monkey', 'camel', zoo
# 输出总长度(注意第一个加进来之后就成了一个二维数组)
print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)
# 输出第二个元组松的元素
print('Animals brought from old zoo are', new_zoo)
# 输出第二个元组中的第二个元素
print('Last animal brought from old zoo is', new_zoo)
# 输出新元组的总动物数量
print('Number of animals in the new zoo is',
len(new_zoo)-1+len(new_zoo))5.Sequence的使用
# 注意序列的下标是从0开始的
shoplist =
name = 'swaroop'
# Indexing or 'Subscription' operation #
# 索引或“下标(Subscription) ”操作符 #
print('Item 0 is', shoplist)
print('Item 1 is', shoplist)
print('Item 2 is', shoplist)
print('Item 3 is', shoplist)
# 输出负数索引值(逆序来找数据)
print('Item -1 is', shoplist)
print('Item -2 is', shoplist)
# 输出第0个单词字母
print('Character 0 is', name)
#序列切片将包括起始位置,但不包括结束位置
# Slicing on a list #
# shoplist 返回的序列的一组切片将从位置 1 开始,包含位置 2 并在位置 3 时结束
print('Item 1 to 3 is', shoplist)
print('Item 2 to end is', shoplist)
print('Item 1 to -1 is', shoplist)
# shoplist 返回的是整个序列
print('Item start to end is', shoplist)
# 从某一字符串中切片 #
print('characters 1 to 3 is', name)
# 第2个下标以后的所有元素
print('characters 2 to end is', name)
# 从1开始,不包括-1出的位置元素
print('characters 1 to -1 is', name)
# 输出所有的内容
print('characters start to end is', name)
# 设置增长的步长2
print(shoplist)
# 逆序打印输出
print(shoplist)
评论
填写昵称与邮箱即可评论,无需登录。