嵌套列表元素出现次数统计:代码无法运行求助
嵌套列表单词统计解决方案
我来帮你搞定这两个统计需求!先假设你的数据结构是类似这样的嵌套列表(如果结构不一样你可以调整下代码逻辑哈):
word_lists = [['das', 'ist', 'das'], ['ein', 'test', 'das'], ['noch', 'ein', 'beispiel']] target_word = 'das'
一、统计指定单词在单个内层列表中的出现次数
直接用列表自带的count()方法就可以搞定,指定内层列表的索引就行:
# 比如统计第一个内层列表(索引为0)中'das'的次数 single_list_count = word_lists[0].count(target_word) print(f"第一个内层列表中'{target_word}'出现了{single_list_count}次") # 输出:第一个内层列表中'das'出现了2次
如果想更灵活,可以写个小函数,方便指定任意内层列表:
def count_in_single_sublist(nested_list, word, sublist_index): # 先检查索引是否合法 if sublist_index < 0 or sublist_index >= len(nested_list): return "指定的内层列表索引不存在哦" return nested_list[sublist_index].count(word) # 调用示例 print(count_in_single_sublist(word_lists, 'das', 0)) # 输出2
二、统计指定单词在所有列表中的总出现次数
用生成器表达式遍历每个内层列表,累加每个子列表的统计结果就好:
total_count = sum(sublist.count(target_word) for sublist in word_lists) print(f"所有列表中'{target_word}'总共出现了{total_count}次") # 输出:所有列表中'das'总共出现了3次
同样可以封装成函数,方便重复调用,还能避免非列表内层元素报错:
def count_total_in_nested_list(nested_list, word): total = 0 for sublist in nested_list: if isinstance(sublist, list): total += sublist.count(word) return total # 调用示例 print(count_total_in_nested_list(word_lists, 'das')) # 输出3
如果之前运行报错,大概率是列表结构不符合预期(比如内层不是列表、索引越界),或者调用方法时参数传错了,你可以对照上面的代码调整下自己的实现~
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

