您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PythonTipsandTraps(一)

2024/12/20 10:11:54发布15次查看
1、如果想得到一个列表的index和内容,可以通过enumerate快速实现
drinks = ['coffee','tea', 'milk', 'water']for index, drink in enumerate(drinks):    print ('item {} is {}'.format(index, drink))#result# item 0 is coffee# item 1 is tea# item 2 is milk# item 3 is water
2、python 中的set, 是一个无序不重复元素集,可以非常方便的进行关系测试和消除重复元素
# deduplicate a list fastprint (set(['ham', 'eggs','bacon','ham']))# result# {'ham', 'eggs', 'bacon'}
# compare list to find difference/similarities # {} without key:value pairs makes a setmenu = {'pancakes', 'ham', 'eggs', 'bacon'}
new_menu = {'coffee', 'ham', 'eggs', 'bagels', 'bacon'}
new_items = new_menu.difference(menu)print ('try our new', ', '.join(new_items))# result: try our new coffee, bagelsdiscontinued_items = menu.difference(new_menu)print ('sorry, we no longer have', ', '.join(discontinued_items))# result: sorry, we no longer have panckes
old_items = new_menu.intersection(menu)print ('or get the same old', ', '.join(old_items))# result: or ger the same old eggs, ham, baconfull_menu = new_menu.union(menu)print ('at one time or another, we have served ', ','.join(full_menu))
3、namedtuple    生成可以使用名字来访问元素内容的tuple 子类,非常方便
import collectionshttp:
lightobject = collections.namedtuple('lightobject', ['shortname', 'otherprop'])
n = lightobject(shortname = 'something', otherprop = 'something else')
n.shortname  # something
4、deque 双段队列,最大好处就是可以从头部添加和删除对象 popleft()、 appendleft()
import collections
d = collections.deque('123456')print d.popleft()  # '1'd.appendleft('7')print d #  deque(['7','2','3','4','5','6'])
5、counter 同样是collections 中的,主要用来计数
import collections
c = collections.counter('abcab')print c #couner({'a':2,'b':2,'c':1}
elements 方法返回一个迭代器,将生成counter 知道的所有元素;most_common(n)生成一个序列,包含最常用的输入值及相应计数
 以上就是pythontipsandtraps(一)的内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product