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

如何基于用户输入在住宿列表中匹配子串?代码返回空列表

住宿地点搜索函数返回空列表的解决方法

问题描述

我有一组住宿地点的元组列表,希望实现用户输入字符串后,搜索列表并输出匹配结果(例如输入Bec时显示Becketts),但目前编写的Python搜索函数始终返回空列表。

住宿地点列表

places = [
    ('Becketts', 'Bed and Breakfast', '11 Bellevue Terrace Southsea Portsmouth PO5 3AT'),
    ('Charles Hope Apartments', 'Apartment', 'Exchange Court Southampton SO14 3SB'),
    ('Claremont Guest House', 'Bed and Breakfast', '33-35 The Polygon Southampton SO15 2BP', 8),
    ('Farmhouse Hotel', 'Hotel', 'Burrfields Rd Portsmouth PO3 5HH'),
    ('Ferry House Lodge', 'Bed and Breakfast', '472 Mile End Rd Portsmouth PO2 7BX'),
    ('Freemantle Solent Lodge', 'Bed and Breakfast', 'Park Rd Freemantle Southampton SO15 3BB'),
    ('Hammersmith Rooms', 'Hostel', '28-30 Bute Gardens London, W6 7DS')
]

原搜索函数代码

def search_name():
    response = input()
    responses = [match for match in places if response in match]
    print(responses)

问题原因

原代码中response in match是判断输入字符串是否存在于整个元组对象中,而非元组的第一个元素(住宿名称)里,这就导致永远匹配不到结果,返回空列表。

修正后的代码

def search_name():
    response = input("请输入搜索关键词:").strip()
    # 匹配元组第一个元素(住宿名称),支持大小写不敏感搜索
    responses = [match for match in places if response.lower() in match[0].lower()]
    print(responses)

修正说明

  • 定位到元组的第一个元素match[0],确保搜索的是住宿名称
  • 添加.lower()实现大小写不敏感搜索,用户输入bec或BEC都能匹配到Becketts
  • 用.strip()去除输入的前后空格,避免因误输入空格导致匹配失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:42:46