상세 컨텐츠

본문 제목

Collections Module

Python

by techbard 2016. 4. 29. 13:22

본문

반응형

# Counter collection


from collections import Counter


l = [1, 1, 1, 2, 3]


print(Counter(l))


s = "asadadasadadada"


print(Counter(s))


ss = "How many times does each word show up in this sentence word word"


words = ss.split()


print(Counter(words))


c = Counter(words)


print(c.most_common(4))


# 결과

Counter({1: 3, 2: 1, 3: 1})

Counter({'a': 8, 'd': 5, 's': 2})

Counter({'word': 3, 'show': 1, 'many': 1, 'in': 1, 'each': 1, 'sentence': 1, 'up': 1, 'times': 1, 'How': 1, 'does': 1, 'this': 1})

[('word', 3), ('show', 1), ('many', 1), ('in', 1)]



# defaultdict


from collections import defaultdict


d = defaultdict(object)

d['one']

for item in d:

print(item)


d = defaultdict(lambda : 0)

print(d['one'])


d['two'] = 2

for k, v in d.items():

print("Key: {}, Value: {}".format(k, v))


# 결과

one

0

Key: one, Value: 0

Key: two, Value: 2


# OrderedDict


from collections import OrderedDict


d = OrderedDict()


d['a'] = 1

d['b'] = 2

d['c'] = 3

d['d'] = 4


for k, v in d.items():

print(k, v)


# 결과

a 1

b 2

c 3

d 4


# namedtuple


from collections import namedtuple


Dog = namedtuple('Dog', 'age breed name')


sam = Dog(age = 2, breed = 'Lab', name = 'sammy')


print(sam.age)


print(sam[0])


# 결과

2

2


# deque


from collections import deque


q = deque([1, 2, 3])


q.append(4)

q.append(5)


print(q)


q.popleft()


print(q)


q.pop()


print(q)


# 결과

deque([1, 2, 3, 4, 5])

deque([2, 3, 4, 5])

deque([2, 3, 4])


# list enumerate


ls = [1, 2, 3]


for index, value in enumerate(ls):

print("value: {}, index: {}".format(value, index))


# 결과

value: 1, index: 0

value: 2, index: 1

value: 3, index: 2


반응형

관련글 더보기

댓글 영역