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

如何打印列值等于用户指定值的所有行?Python代码仅匹配首行问题排查

问题排查及解决方案

根因分析

  • 核心问题是变量重名覆盖:存储用户输入分类的变量名为category,但在匹配成功后的格式化逻辑里,又用了同名变量接收分类的格式化字符串。第一次匹配成功时,原本存储用户输入的category值就会被覆盖,后续循环的匹配条件row[7] == category自然无法再命中其他符合条件的行。

修复方案

仅需修改格式化分类信息时的变量名,避免和全局的用户输入变量重名即可,修复后的代码如下:

contact_list = [[1,'Athena','Brizell','Vitz','9 Northview Hill',5888510700,344-241-3276,'Development','4/27/2021','10/29/2021','Athena Brizell'],
[2,'Isadore','Ander','Wordtune','72660 Orin Road',4848283832,877-155-7495,'Office_fitting','4/25/2021','9/26/2021','Isadore Ander'],
[3,'Hannis','Matches','Realpoint','847 Schurz Park',9052187780,368-121-1215,'Office_fitting','1/8/2021','9/4/2021','Hannis Matches'],
[4,'Cindee','Breadon','Gigashots','3 Bultman Way',4543988898,155-423-5293,'Support','4/25/2021','6/29/2021','Cindee Breadon'],
[5,'Baron','Arnao','Thoughtstorm','856 Blackbird Road',9831465576,207-486-1010,'Development','4/30/2021','10/28/2021','Baron Arnao'],
[6,'Laureen','Kearney','Dablist','70525 Texas Terrace',6091413184,602-843-9500,'Office_fitting','3/3/2021','9/3/2021','Laureen Kearney']]

category = input('Please enter the category you wish to display contacts for (Development/Office_fitting/Support: ')

for row in contact_list:
    if row[7] == category:
        firstname = f'Firstname: {row[1]}\n'
        lastname = f'Lastname: {row[2]}\n'
        company = f'Company: {row[3]}\n'
        address = f'Address: {row[4]}\n'
        landline = f'Phone: {row[5]}\n'
        mobile = f'Mobile: {row[6]}\n'
        # 修改变量名,避免覆盖用户输入的category
        category_info = f'Category: {row[7]}\n'
        date_created = f'Date Created: {row[8]}\n'
        date_modified = f'Date Updated: {row[9]}\n'
        print(firstname, lastname, company, address, landline, mobile, category_info, date_created, date_modified)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:24:04