Python中的List和tuple
来源:互联网 发布:开淘宝店多久能赚钱啊 编辑:程序博客网 时间:2024/05/21 13:54
数组or元组?
在python称之为 list和tuple
list
list下标也是和Java等一样,是从0开始的
空列表: L = []
含有元素的一位列表: L = [1, 2, 3, 4],与Java等不同的是L =[1, 2, ‘one’]这种多类型组成的列表在Python中也是支持的。
多维list:
L = [
[1, 2, 3, 4],
[‘one’, ‘two’, ‘three’],
[‘1.11’, ‘2.22’, ‘3.33’]
]
很好理解;
可以用len(list)来获取的list的长度
list可以有append() (list.append(obj)), insert()方法(list.insert(index, obj))
tuple
L = (1, 2, 3)
可以
L = (1, 2, 3)print(L)'''输出(1, 2, 3)'''
所以是不是和list特别像,但是tuple不支持append()和insert()等方法
其他和list一样。
list和tuple
比如有一个L = [1, 2, 3, 4]
Python的厉害之处在于
L[-1] ,L[-2]这种 都支持(在Java就一巴掌扇过来,下标越界)
所以L[-1]的意思就是获取L的倒数第一个元素;
同理L = (1, 2, 3, 4)
list和tuple杂交
L = (1, 2, [‘one’, ‘two’, ‘three’])
那么L[0] = 1, L[1] = 2, L[2][0] = ‘one’, L[2][1] = ‘two’….太牛逼了
其中当只有一个元素时:
L = (1, )
L2 = [1]
print(L)
print(L2)
元组需要这样定义,不然L = (1),会输出1这个数,而不是一个元组
list的遍历循环
比如有一个L = [1, 2, 3, 4]
L = [1, 2, 3, 4]for a in L: #注意冒号 print(a)
而Java,C++中一般遍历都是
for ( int i = 0; i < n; i++ )
Python中的遍历称之为迭代
有点像Java中for-each循环
//Java for-eachint[] a = {1, 2, 3};for ( int k:a ) { System.out.println(k);}
更自由潇洒的Python迭代
比如有L = [(1, 1), (2, 2), (3, 3)]
for x, y in L: print((x, y))
此外
类似Java中for( int i = 0; i < n; i++ )
Python 有潇洒的写法
for k in range(0, n):#从0开始迭代n个
- python中的list和tuple
- Python中的List和tuple
- python中的list和tuple
- python中的list和tuple
- Python中的List和Tuple
- Python中的List,Tuple和Dictionary
- python中的list,tuple 和 dictionary
- Python list和tuple
- Python list和tuple
- python的list和tuple
- python的list 和 tuple
- python 使用list和tuple
- Python List 、 tuple和dict
- Python(3)--list和tuple
- python的list和tuple
- Python(List和Tuple类型)
- python list和tuple区别
- Python中list和tuple
- 算法题3:二叉树度为0的结点个数(创新工场笔试题)
- JS的初始化问题
- JS--第七天
- speedtest-cli测试网速
- 并查集详解(转自大神博客)
- Python中的List和tuple
- CSS中line-height与height的区别?
- HTML5初步了解
- Quartz任务调度框架学习四(Quartz集成Spring及在项目中的应用)
- MFC消息机制
- anroid AudioTrack 基本使用
- 对话框上滑向上移动消失,下滑向下移动消失
- nodejs 中关于 exports 和 module.exports 的区别
- scanf函数输入多个字符串时间隔符的失效及解决办法