您的位置:首页 > 编程语言 > Python开发

python的列表、元组、序列、字典、集合的简单说明

2018-04-07 10:30 726 查看
# 介绍列表、元组、字典、序列的用法

# 列表 ---类似C++的vector,不定长数组
# 添加 mylist.append(x)   删除 del mylist
排序 mylist.sort()
n = int(input())
mylist = []  # 初始化
for i in range(0, n):
x = int(input())
mylist.append(x)  # 添加列表元素
print('列表元素为:', end='')
print(mylist)
print('列表经过排序之后:', end='')
mylist.sort()  # 列表排序
for i in mylist:
print(i, end=' ')
print('\n删除mylist[1]这个元素后:',end='')
del mylist[1]  # 删除列表元素
for i in range(0,len(mylist)):  # range为左闭右开
print(mylist[i], end=' ')
print('\n列表的复制:',end='')
newmylist = mylist
print(newmylist)
print('-------------------------------')

# 元组---他可以将列表以及元素混合封装在一起,是不可改变的
mytuple = (1, 2, (4, 5))
print('元组元素为:',end='')
print(mytuple)
newtuple = (0, mytuple)
print('新元组元素为:', end='')
print(newtuple)
print('The newtuple[1][2][0] is:{}'.format(newtuple[1][2][0]))
print('-------------------------------')

# 序列---主要用于切片操作
# 其中字符串,列表,元组都可以看作序列,并进行切片操作
# string[:]代表整个序列,string[2:5]左闭右开,string[2:-1]其中-1代表最后一个元素,左闭右开就不包括,-2倒数第二
# mylist[0:-1:2],开头到结尾,且步长为2,第一个冒号不可缺省,其余都可以缺省,缺前者就从开头开始,后者就到结尾结束

string = 'Never say never!'
mylist = [5, 9, 4, 2, 5, 0]
print('The outcome of string[0:5] is: ', end=' ')
for i in string[0:5]:
print(i, end='')
print('\nThe answer of mylist[:-1:2] is: ', mylist[:-1:2])
print('-------------------------------')

# 字典---相当于c++中的map,是键与值的对应 key: value
cnt = {'小米': 'Mi', '华为': 'HuaWei'}
for name, loge in cnt.items():  # 将每一种映射输出
print('The Chinese name is: {} and the loge is:{} '.format(name, loge))
cnt['欧珀'] = 'oppo'  # 添加映射
string = '欧珀'
print('The Chinese name is: {} and the loge is:{} '.format(string, cnt[string]))
print('-------------------------------')

# 集合---和C++中set一直,多个重复元素,只储存一个
# 声明: myset = set([])   添加 myset.add(x)   删除 myset.remove(x)
# 判断是否存在 if x in myset:    取交集 myset&yourset
# 判断是否包含 myset.issuperset(yourset) 返回bool     复制 yourset = myset.copy()

myset = set(['Mi', 'Huawei', 'Vivo'])
yourset = set(['Apple'])
string = 'Oppo'
if string not in myset:
myset.add(string)
myset.add(string)  # 添加两次也只添加了一个
print('Myset is:', myset)
else:
print('It already in container.')
yourset = myset.copy()  # 复制时覆盖了原来的apple
print('Yourset is: ', end=' ')
for i in yourset:
print(i, end=' ')
if myset.issuperset(yourset):  # 相等时同样返回True
print('\nI\'m the father.')
else:
print('You\'re the brother.')
yourset.remove(string)
print('The same of us: ', myset & yourset)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息