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)
相关文章推荐
- Python 列表、元组、集合、字典、Json、数组、矩阵 简单示例说明
- python 列表,元组,字典,集合简单总结
- 1900页Python系列PPT分享二:Python序列(列表、元组、字典、集合)(154页)
- python的列表,元组,字典,序列,字符串的简单解说
- Python中数据结构 列表 元组 字典 序列
- python 列表 元组 字典 集合 的区别
- Python数据结构:序列(列表[]、元组())与映射(字典{})语法总结
- python中列表、元组、字典和集合
- Python中数据结构 列表 元组 字典 序列
- python的列表(List),元组(Tuple),集合(Set),字典(Dict)
- python 第十二周 元组、列表、字典、序列
- Python基础:列表,元组,字典,集合相关基本操作
- Python 入门学习 -----变量及基础类型(元组,列表,字典,集合)
- Python进阶(九):列表,元组,字典,集合的同异
- python序列的三种类型:列表、元组、字典
- python笔记2 (列表,元组,字典,集合)
- Python中几种数据结构的整理,列表、字典、元组、集合
- Python数据结构中列表,字典,元组,集合的总结
- python3的列表、元组、集合、字典操作
- python的列表,元组和字典简单介绍