python list列表操作
来源:互联网 发布:vr需要学什么编程语言 编辑:程序博客网 时间:2024/05/21 11:19
python list列表操作
list是python内置的列表类型。list和string有点相似,使用len()和[]来操作里面的元素,而且第一个元素下标示从0开始的。
colors = ['red', 'blue', 'green']print colors[0] ## redprint colors[2] ## greenprint len(colors) ## 3
把list赋值给一个变量,它并没有复制一份,只是增加了一个指针。它在内存中还是一个list。
b = colors ## Does not copy the list
For and IN遍历list
for var in list语法通过遍历,把每个元素赋值给var,然后就可以在循环中操作var了。注意:当在遍历list的时候不要添加和删除list里元素
squares = [1, 4, 9, 16]sum = 0for num in squares:sum += numprint sum ## 30
in可以很容易的来测试是否有个元素在list中。它返回值为True或者False
list = ['larry', 'curly', 'moe']if 'curly' in list:print 'yay'
string也可以像list一样使用for in结构。 如for ch in s: print ch 将打印string里的每个字符。
list列表的其他一些妙用
去掉列表中每个元素头尾的空格
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [str.strip() for str in freshfruit] ['banana', 'loganberry', 'passion fruit']
把列表中,大于3的元素,乘以2
>>> vec = [2, 4, 6] >>> [2*x for x in vec if x > 3] [8, 12]
把列表1的每一个元素和列表2的每一个元素相乘
>>> lst1 = [2, 4, 6] >>> lst2 = [4, 3, -9] >>> [x*y for x in lst1 for y in lst2] [8, 6, -18, 16, 12, -36, 24, 18, -54]
获取[0-10]的平方
[x**2 for x in range(10)]
或
map(lambda x : x*x, range(10))
获取[0-10]中奇数的平方
[x**2 for x in filter( lambda x : x%2, range(10) )]
list去重
比较容易记忆的是用内置的set
l1 = ['b','c','d','b','c','a','a']l2 = list(set(l1))print l2
还有一种据说速度更快的,没测试过两者的速度差别
l1 = ['b','c','d','b','c','a','a']l2 = {}.fromkeys(l1).keys()print l2
这两种都有个缺点,祛除重复元素后排序变了:
['a', 'c', 'b', 'd']
保持原来的list可以使用下面的方法:
l1 = ['b','c','d','b','c','a','a']l2 = sorted(set(l1),key=l1.index)print l2 #output ['b', 'c', 'd', 'a']
0 0
- Python 列表(list)操作
- Python 列表(list)操作
- Python 列表(list)操作
- Python 列表(list)操作
- python list列表操作
- Python 列表(list)操作
- Python 列表(list)操作
- Python 列表(list)操作
- Python List列表操作
- Python 列表(List)操作
- python--列表list()操作
- python--列表list()操作
- Python列表操作(list)
- Python的列表操作List
- 【python系列】列表list的操作讲解
- (转载)Python 列表(list)操作
- python入门之列表list删除操作
- python list(列表)操作用法总结
- uva437 - The Tower of Babylon(DAG上的DP)
- leetcode LRU Cache(**)
- html元素标签
- 大数相除
- LeetCode Swap Nodes in Pairs
- python list列表操作
- open ps failed. errno: Permission denied
- 深度探索C++对象模型----Data语义学
- Hdu4111Alice and Bob(dp+博弈论)
- 类、抽象类、接口
- &--引用声明符
- Java类加载机制
- 不要62 hdoj 2089
- 博弈