python:(3)使用list和tuple
来源:互联网 发布:云计算 日语 编辑:程序博客网 时间:2024/05/22 01:30
1.list
新建列表;
>>> classmates = ['Michael','Bob','Tracy']>>> classmates['Michael', 'Bob', 'Tracy']
看长度及查询:
>>> len(classmates)3>>> classmates[0]'Michael'>>> classmates[1]'Bob'>>> classmates[2]'Tracy'>>> classmates[-1]'Tracy'>>> classmates[-2]'Bob'>>> classmates[-3]'Michael'
增:
>>> classmates.append('Adam')>>> classmates['Michael', 'Bob', 'Tracy', 'Adam']>>> classmates.insert(1,'Jack')>>> classmates['Michael', 'Jack','Bob', 'Tracy', 'Adam']
删:
>>> classmates.pop()'Adam'>>> classmates['Michael','Jack', 'Bob', 'Tracy']>>> classmates.pop(1)'Jack'>>> classmates['Michael','Bob', 'Tracy']
改:
>>> classmates[1] = 'Sarah'>>> classmates['Michael', 'Sarah', 'Tracy']
嵌套:
>>> L = ['Aplle',123,True]>>> L['Aplle', 123, True]>>> s = ['Python','java',L,'scheme']>>> s['Python', 'java', ['Aplle',123,True], 'scheme']>>> len(s)4>>> s[2]['Aplle',123,True]>>> s[2][1]123
2.tuple
2.1
另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改.
>>> c = ('Micheal','Bob','ssss')>>> c.pop()Traceback (most recent call last): File "<pyshell#44>", line 1, in <module> c.pop()AttributeError: 'tuple' object has no attribute 'pop'
2.2
但是,要定义一个只有1个元素的tuple,如果你这么定义:
>>> t = (1)>>> t1
定义的不是tuple,是1这个数!这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1。
所以,只有1个元素的tuple定义时必须加一个逗号,,来消除歧义:
>>> t = (1,)>>> t(1,)
Python在显示只有1个元素的tuple时,也会加一个逗号,,以免你误解成数学计算意义上的括号。
2.3
最后来看一个“可变的”tuple:
>>> t = ('a', 'b', ['A', 'B'])>>> t[2][0] = 'X'>>> t[2][1] = 'Y'>>> t('a', 'b', ['X', 'Y'])
2.4
廖雪峰教程练习:
练习:
请用索引取出下面list的指定元素:# -*- coding: utf-8 -*-L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa']]# 打印Apple:print(?)# 打印Python:print(?)# 打印Lisa:print(?)
答:
>>> L = [['Apple','Google','Microsoft'],['Java','Python','Ruby','PHP'],'Adam','Bart','Lisa']>>> L[['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], 'Adam', 'Bart', 'Lisa']>>> print(L[0][1])Google>>> print(L[0][0])Apple>>> print(L[0][1])Google>>> print(L[4])Lisa
阅读全文
0 0
- python:(3)使用list和tuple
- python学习(3)python基础、使用list和tuple
- python 使用list和tuple
- python 使用list和tuple
- python使用list和tuple
- 开始Python -- List和Tuple(3)
- Python(3)--list和tuple
- Python学习(二)---使用list和tuple
- 【Python学习笔记】使用list和tuple
- python学习笔记使用list和tuple
- Python list和tuple
- Python list和tuple
- 使用list和tuple
- 使用list和tuple
- 使用list和tuple
- 使用list和tuple
- 使用list和tuple
- 使用list和tuple
- apache做反向代理服务器
- 数据库——Oracle中的通配符
- 如何适配iOS11和iPhoneX
- [bzoj2152]聪聪可可——点分治
- 【云栖大会精华汇】历届云栖大会精彩资料大放送,一篇看尽云栖大会前世今生
- python:(3)使用list和tuple
- Android 布局属性大全查找方便
- 怎么发表期刊方法步骤
- python:(4)条件判断
- 2-1 Point类的定义
- .net 简易数据库操作框架1.1
- Java 异常机制,异常的结构,运行时异常和非运行时异常
- python 引用和拷贝
- Java学习笔记之集合(六):TreeSet集合的实现原理