Python Tips and Traps(一)

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 fast
print (set(['ham', 'eggs','bacon','ham']))
# Result
# {'ham', 'eggs', 'bacon'}
# compare list to find difference/similarities 
# {} without "key":"value" pairs makes a set
menu = {'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, bagels

discontinued_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, bacon

full_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)生成一个序列,包含最常用的输入值及相应计数

转载于:https://www.cnblogs.com/siriuswang/p/4239119.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值