获取列表中每个所需项目的总和
我有一段能正常工作的代码,但我在想有没有更好的方法来实现它。
这个函数会计算每个指定项目出现的次数总和,并把结果以列表的形式返回。
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]
2 个回答
0
你可以使用内置的 count() 函数:
def question10(ipaddresses: list[str]):
none_count = ipaddresses.count(None)
host_count = ipaddresses.count('129.128.1.1')
target_count = ipaddresses.count('192.128.1.4')
return [none_count, host_count, target_count]
3
你可以使用collections库里的Counter。
它的用法大概是这样的:
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]