python技巧
来源:互联网 发布:帆船逆风行驶原理 知乎 编辑:程序博客网 时间:2024/05/22 17:19
1,去重
Python列表去掉重复元素的一种方法:
>>> L = [1, 2, 3, 4, 1, 2, 3, 4, 5]
>>> [x for x in L if x not in locals()['_[1]']]
[1, 2, 3, 4, 5]
或者
list(set(a))
2,对象排序
list 排序在包含某元素的列表中依据某个属性排序是一个很常见的操作。例如这里我们先创建一个包含 person 的 list:
class Person(object):
def __init__(self, age):
self.age = age
persons = [Person(age) for age in (14, 78, 42)]
传统的方式是:
def get_sort_key(element):
return element.age
for element in sorted(persons, key=get_sort_key):
print "Age:",
element.age更加简洁、可读性更好的方法是使用 Python 标准库中的 operator 模块:
from operator import attrgetter
for element in sorted(persons, key=attrgetter('age')):
print "Age:",
element.ageattrgetter 方法优先返回读取的属性值作为参数传递给 sorted 方法。operator 模块还包括 itemgetter 和 methodcaller 方法,作用如其字面含义。
3,三元操作
return 1 if v==0 else v
或者
return v==0 and 1 or v
4,读取文件
with open("d:/1.log") as fp:
line = fp.readline()
print line
5,格式化字符串
values= {'name':name,'message':message}
print ('Hello%(name)s,you have%(message)i'%values)
- python技巧
- python技巧
- python技巧
- python技巧
- Python 技巧
- python技巧
- python-技巧
- python技巧
- python技巧
- python技巧
- Python技巧
- Python技巧
- Python 技巧
- # Python 技巧
- python技巧31[python Tip2]
- Python技巧-警惕关键字
- Python技巧汇总
- Python技巧 ---- 不断更新中
- ddos
- django使用innodb类型表commit
- IE6 IE7 IE8 未按预期方式处理 content-type 为 text/plain 的内容
- UTF与BOM之间的关系
- 【BIOS如何优化】
- python技巧
- rel=’external nofollow’
- 切线空间计算
- 大数据:频繁项集
- mysqldb按字典方式取数据
- SQL注入
- 无线共享上网
- c语言数字类型总结
- 黑马程序员—JAVA内部类