我有一个工作代码,但我想知道是否有更好的方法来做到这一点。
该函数获取每个指定项目的出现次数总和,并将它们作为列表返回。
def question10(ipaddresses: list[str]):
none_count = sum(1 if x is None else 0 for x in ipaddresses)
host_count = sum(1 if x == '129.128.1.1' else 0 for x in ipaddresses)
target_count = sum(1 if x == '192.128.1.4' else 0 for x in ipaddresses)
return [none_count, host_count, target_count]
您可以使用集合库中的计数器。
它看起来像这样:
from collections import Counter
def question10(ipaddresses: list[str]):
counter = Counter(ipaddresses)
return [counter[None], counter['129.128.1.1'], counter['192.128.1.4']]
请注意,
list[str]
语法仅适用于较新的Python版本,例如Python 3.9及更高版本。
对于旧版本,您可以使用类似以下内容:
from typing import List
from collections import Counter
def question10(ipaddresses: List[str]):
counter = Counter(ipaddresses)
return [counter[None], counter['129.128.1.1'], counter['192.128.1.4']]
但是,这些的用例将保持不变。 例如列表:
ipaddresses = ['192.128.1.1', '192.128.1.4', '129.128.1.1',
'129.128.1.1', '129.128.1.4']
在这两种情况下都应该输出
[0, 2, 1]