Python中(zip、enumerate、collections、defaultdict、Counter)函数使用

zip

  • 把两个可迭代的内容生成一个可迭代的tuple元素类型组成的内容
l1 = [1,2,3,4,5]
l2 = [11,22,33,44,55]
z = zip(l1,l2)
for i in z:
    print(i)

>>>
(1, 11)
(2, 22)
(3, 33)
(4, 44)
(5, 55)

enumerate

  • 跟zip功能比较像
  • 对可迭代对象里的每一元素,配上一个索引,然后索引和内容构成tuple类型
l1 = [11,22,33,44,55]
em = enumerate(l1)
l2 = [i for i in em]
print(l2)

>>>
[(0, 11), (1, 22), (2, 33), (3, 44), (4, 55)]

----
em = enumerate(l1, start = 100)
l2 = [i for i in em]
print(l2)

>>>
[(100, 11), (101, 22), (102, 33), (103, 44), (104, 55)]

collections模块

  • namedtuple
    • 是一个可命名的tuple
  • deque
    • 比较方便的解决了频繁的删除插入带来的问题
import collections
Point = collections.namedtuple("Point",['x','y'])
p = Point(11,22)
print(p.x)
print(p[0])

>>>
11
11

-----
Circle = collections.namedtuple("Circle",['x','y','r'])
c = Circle(100,150,50)
print(c)

>>>
Circle(x=100, y=150, r=50)
from collections import deque
q = deque(['a', 'b', 'c'])
print(q)
q.append("d")
print(q)
q.appendleft('x')
print(q)

>>>
deque(['a', 'b', 'c'])
deque(['a', 'b', 'c', 'd'])
deque(['x', 'a', 'b', 'c', 'd'])

defaultdict

  • 当直接读取dict不存在的属性时,直接返回默认值
from collections import defaultdict
func = lambda:"dana"
d2 = defaultdict(func)
d2["one"] = 1
d2["two"] = 2
print(d2['one'])
print(d2['four'])

>>>
1
dana

Counter

  • 统计字符串个数
from collections import Counter
c = Counter("afgdafgjhdsfha") # 括号中要放入可迭代的东西
print(c)

>>>
Counter({'a': 3, 'f': 3, 'g': 2, 'd': 2, 'h': 2, 'j': 1, 's': 1})

----
s = ["dana","haha","dana","hehe","xixi","hehe"]
c = Counter(s)
print(c)

>>>>
Counter({'dana': 2, 'hehe': 2, 'haha': 1, 'xixi': 1})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值