有沒有一種簡單的方法來計算串列中有多少特定型別的元素?
這就是我的想法和我嘗試過的。
ex_list = ["string", "data", "item", 1, 3, {3: "im dict"}, "im_item"]
print(ex_list.count(int)) # -> 0, should return 2
print(ex_list.count(type(str))) # -> 0, should return 4
我知道有一些解決方法(使用回圈等),但我想知道是否有像只使用一個函式(如計數函式等)一樣簡單的東西。
uj5u.com熱心網友回復:
您可以將Counter類 (from collections) 與到型別的映射一起使用:
from collections import Counter
ex_list = ["string", "data", "item", 1, 3, {3: "im dict"}, "im_item"]
typeCounts = Counter(map(type,ex_list))
>>> typeCounts
Counter({<class 'str'>: 4, <class 'int'>: 2, <class 'dict'>: 1})
>>> typeCounts[int]
2
這將在 O(n) 時間內進行初始計數,typeCounts[type]此后每次使用都將是 O(1)。
uj5u.com熱心網友回復:
from operator import countOf
countOf(map(type, ex_list), int)
在線試試吧!
檔案
基準:
644 ns 646 ns 671 ns countOf(map(type, ex_list), int)
2102 ns 2149 ns 2154 ns Counter(map(type, ex_list))[int]
1125 ns 1150 ns 1183 ns sum(type(x) is int for x in ex_list)
具有 1000 倍長串列的基準測驗:
392 μs 396 μs 397 μs countOf(map(type, ex_list), int)
684 μs 696 μs 699 μs Counter(map(type, ex_list))[int]
854 μs 887 μs 896 μs sum(type(x) is int for x in ex_list)
因此,對于您的問題所要求的“特定型別”,它是這些方法中最快的,但Counter如果您想要多種型別,則可能會更快。
基準代碼(在線試用!):
from timeit import repeat
setup = '''
from operator import countOf
from collections import Counter
ex_list = ["string", "data", "item", 1, 3, {3: "im dict"}, "im_item"]
'''
E = [
'countOf(map(type, ex_list), int)',
'Counter(map(type, ex_list))[int]',
'sum(type(x) is int for x in ex_list)',
]
print('example list:')
for _ in range(3):
for e in E:
number = 100000
times = sorted(repeat(e, setup, number=number))[:3]
print(*('M ns ' % (t / number * 1e9) for t in times), e)
print()
print('1000 times longer list:')
setup = 'ex_list *= 1000'
for _ in range(3):
for e in E:
number = 100
times = sorted(repeat(e, setup, number=number))[:3]
print(*('M μs ' % (t / number * 1e6) for t in times), e)
print()
uj5u.com熱心網友回復:
我不會將回圈稱為解決方法;對此的任何解決方案都將使用回圈,無論它是用 Python 撰寫的還是在后臺撰寫的。所以,這是一個使用 的回圈解決方案isinstance(),它允許子類。
def type_count(iterable, type_):
return sum(isinstance(x, type_) for x in iterable)
>>> type_count(ex_list, int)
2
>>> type_count(ex_list, str)
4
如果您想使用該Counter解決方案但允許子類,您可以通過每種型別的方法決議順序(MRO),如下所示:
from collections import Counter
typeCounts = Counter(map(type, ex_list))
for t, n in list(typeCounts.items()): # list() since the dict will change size
for parent in t.__mro__[1:]:
typeCounts[parent] = n
>>> typeCounts[int]
2
>>> typeCounts[object] == len(ex_list)
True
檔案: class.__mro__
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/324975.html
上一篇:我正在使用Socat在一個Expect腳本中打開一個與cisco交換機的串行連接。我能夠登錄到交換機,但Expect命令不作業。
