程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Counter, defaultdict, ordereddict, namedtuple, deque in Python collections

編輯:Python

1 Counter

Count , The following example , Find the number of repetitions of elements in the list :

from collections import Counter
device_temperatures = [13.5, 14.0, 14.0, 14.5, 14.5, 14.5, 15.0, 16.0]
temperature_counter = Counter(device_temperatures)
# Counter({14.5: 3, 14.0: 2, 13.5: 1, 15.0: 1, 16.0: 1})
print(temperature_counter)
print(type(temperature_counter)) # <class 'collections.Counter'>
print(temperature_counter[13.5]) # 1
print(temperature_counter[14.0]) # 2
print(temperature_counter[14.5]) # 3
print(temperature_counter[15.0]) # 1
print(temperature_counter[16.0]) # 1

2 defaultdict

example 1

The following code will generate an error KeyError, because my_dict Not for 'hi' Of key:

my_dict={
'hello':5}
print(my_dict['hi'])
# Traceback (most recent call last):
# File "<string>", line 4, in <module>
# KeyError: 'hi'
# > 

By contrast , defaultdict Never cause KeyError.
Here's an example from tuple A list of components coworkers, List the schools that everyone attended :

coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'), ('Rolf', 'Cambridge'), ('Charlie', 'Manchester')]

Now you have to get one dictionary:

{

'Rolf': ['MIT', 'Cmbridge'],
'Jen': ['Oxford'],
'Charlie': ['Manchester']
}

The general way of writing :

coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'), ('Rolf', 'Cambridge'), ('Charlie', 'Manchester')]
alma_maters = {
} # (alma mater: Alma mater )
for coworker in coworkers:
if coworker[0] not in alma_maters:
alma_maters[coworker[0]] = []
alma_maters[coworker[0]].append(coworker[1])

perhaps :

coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'), ('Rolf', 'Cambridge'), ('Charlie', 'Manchester')]
alma_maters = {
} # (alma mater: Alma mater )
for coworker, place in coworkers:
if coworker not in alma_maters:
alma_maters[coworker] = [] # default value
alma_maters[coworker].append(place)
print(alma_maters)

Change to use defaultdict

from collections import defaultdict
coworkers = [('Rolf', 'MIT'), ('Jen', 'Oxford'), ('Rolf', 'Cambridge'), ('Charlie', 'Manchester')]
# If one of the dictionaries key non-existent , Then... In the parameter is called function
# here function yes list, That is to call list, Get an empty list []
alma_maters = defaultdict(list)
for coworker, place in coworkers:
alma_maters[coworker].append(place)
# If you want to access nonexistent key when , Can throw an exception , Then add the following line 
# alma_maters.default_factory = None
# (None Change to int Time generation 0 value )
print(alma_maters['Rolf']) # ['MIT', 'Cambridge']
print(alma_maters['Jen']) # ['Oxford']
print(alma_maters['Charlie']) # ['Manchester']
print(alma_maters['Anne']) # []

example 2

from collections import defaultdict
my_company = 'Teclado'
coworkers = ['Jen', 'Li', 'Charlie', 'Rhys']
other_coworkers = [('Rolf', 'Apple Inc.'), ('Anna', 'Google')]
# Don't write directly my_company, because defaultdict Accept a function as an argument 
# lambda: my_company return my_company
coworker_companies = defaultdict(lambda: my_company)
for person, company in other_coworkers:
coworker_companies[person] = company
# coworkers[1] yes 'Li', Output default Teclado
print(coworker_companies[coworkers[1]])
# other_coworkers[0][0] yes 'Rolf', Output Apple Inc.
print(coworker_companies[other_coworkers[0][0]])

3 OrderedDict

Here is Pascal Case

seeing the name of a thing one thinks of its function ,OrderedDict It's an ordered dictionary , It refers to that the order of key value pairs is sorted according to the insertion order .

from collections import OrderedDict
o = OrderedDict()
o['Rolf'] = 6
o['Jose'] = 10
o['Jen'] = 3
# keys are always in the order in which they were inserted
# OrderedDict([('Rolf', 6), ('Jose', 10), ('Jen', 3)])
print(o)
o.move_to_end('Rolf') # Move to end 
# OrderedDict([('Jose', 10), ('Jen', 3), ('Rolf', 6)])
print(o)
o.move_to_end('Rolf', last = False) # Move to the end of the reverse , That's the beginning 
# OrderedDict([('Rolf', 6), ('Jose', 10), ('Jen', 3)])
print(o)
o.popitem()
# OrderedDict([('Rolf', 6), ('Jose', 10)])
print(o)

o.popitem(False) : Delete the beginning element

But from Python 3.7 Start ,dictionary Sorted by insert , therefore OrderedDict It's not very useful .
Are dictionaries ordered in Python 3.6+?

4 namedtuple

namedtuple: to tuple as well as tuple Each element in is named

The following code ,account[0],account[1] It is not obvious what they refer to :

account = ('checking', 1850.90)
print(account[0]) # name
print(account[1]) # balance

Use namedtuple:

from collections import namedtuple
account = ('checking', 1850.90)
# The first 1 The parameters are tuple name , Same as the definition name 
# The first 2 The parameters are fields name 
Account = namedtuple("Account", ['name', 'balance'])
accountNamedTuple_1 = Account('checking', 1850.90)
print(accountNamedTuple_1.name, accountNamedTuple_1.balance) # checking 1850.9
accountNamedTuple_2 = Account._make(account)
account_name_2, account_balance_2 = accountNamedTuple_2
print(account_name_2, account_balance_2) # checking 1850.9
accountNamedTuple_3 = Account(*account)
account_name_3, account_balance_3 = accountNamedTuple_3
print(account_name_3, account_balance_3) # checking 1850.9
print(accountNamedTuple_1._asdict()['balance']) # 1850.9
print(accountNamedTuple_2._asdict()['balance']) # 1850.9
print(accountNamedTuple_3._asdict()['balance']) # 1850.9

from csv Documents or database When reading data , Use namedtuple Makes the code easier to understand .

5 deque

deque:double ended queue deque , Use deque Instead of list The first reason is deque Efficient , Second, it guarantees Thread safety (thread safe),deque All operations are thread safe , So in use thread Can be used when deque.

from collections import deque
friends = deque(('Rolf', 'Charlie', 'Jen', 'Anna'))
friends.append('Jose')
friends.appendleft('Anthony')
print(friends) # deque(['Anthony', 'Rolf', 'Charlie', 'Jen', 'Anna', 'Jose'])
friends.pop()
print(friends) # deque(['Anthony', 'Rolf', 'Charlie', 'Jen', 'Anna'])
friends.popleft()
print(friends) # deque(['Rolf', 'Charlie', 'Jen', 'Anna'])

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved