You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python二维列表的元素搜索、替换及计数功能实现问题

问题1 二维列表元素替换失败

原因

当前循环仅遍历了二维列表的外层,fruits[i] 拿到的是每一行的子列表,不可能和输入的单个水果字符串相等,因此不会触发替换逻辑。

解决代码

需要用双层循环同时遍历外层行索引和内层元素索引:

fruits = [ 
    ["Banana", "Apple", "Watermelon", "Apple"],
    ["Apple", "Banana", "Watermelon", "Lemon"]
]
print(fruits)

findFruit = input("Fruit: ")
replaceFruit = input("Replace: ")

# 双层遍历:外层遍历行,内层遍历每行的元素
for row in range(len(fruits)):
    for col in range(len(fruits[row])):
        if fruits[row][col] == findFruit:
            fruits[row][col] = replaceFruit

print(fruits)

问题2 二维列表统计元素出现次数失败

原因

直接调用fruits.count(findFruit)只会统计外层列表中等于findFruit的元素个数,外层元素都是子列表,因此永远返回0。

解决方法

遍历每个子列表,累加每个子列表的count结果即可:

findFruit = input("输入要统计的水果:")
total = 0
for row in fruits:
    total += row.count(findFruit)
print(f"{findFruit} 总出现次数:{total}")

也可以用生成器表达式简化写法:

total = sum(row.count(findFruit) for row in fruits)

内容的提问来源于stack exchange,提问作者Braum Holdren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 04:45:08