Unity C#中如何统计具有特定值的字符串数量?
统计指定字符串的出现次数
手动统计实现
如果不想依赖内置工具,可以用字典手动完成计数:
- 初始化空字典存储每个字符串的出现次数
- 遍历目标字符串列表,更新对应字符串的计数
# 定义目标字符串列表 strings = ["stack", "stack", "overflow", "problem"] count_dict = {} # 遍历统计 for s in strings: if s in count_dict: count_dict[s] += 1 else: count_dict[s] = 1 # 获取指定字符串的计数 print(count_dict["stack"]) # 输出:2 print(count_dict["overflow"]) # 输出:1 print(count_dict["problem"]) # 输出:1
用内置工具简化实现
Python的collections.Counter是专门用于计数的工具类,能更简洁地完成需求:
from collections import Counter strings = ["stack", "stack", "overflow", "problem"] counter = Counter(strings) # 获取指定字符串的计数 print(counter["stack"]) # 输出:2 print(counter["overflow"]) # 输出:1 print(counter["problem"]) # 输出:1 # 查看所有字符串的计数结果 print(counter) # 输出:Counter({'stack': 2, 'overflow': 1, 'problem': 1})
内容的提问来源于stack exchange,提问作者f0rCE
相关产品推荐
相关产品推荐

