如何获取列表中元素的第二个单词

1 投票
3 回答
1371 浏览
提问于 2025-04-17 23:25

给定一个输入字符串,我们需要在存储所有公交车站数据的元组列表中查找,并返回包含与这个字符串匹配的道路的元组列表。注意,大写字母和小写字母被视为相同的字符。如果没有找到匹配的内容,就返回一个空列表。

假设公交车站的数据已经准备好了,也就是说,下面这行代码已经执行过:

bus_stops = read_data('bus_stops.txt')

我有以下内容:

bus_stops.txt
01012,Victoria St,Hotel Grand Pacific

01013,Victoria St,St. Joseph's Ch

01019,Victoria St,Bras Basah Cplx

当执行下面这个表达式时:

lookup_bus_stop_by_road_name(bus_stops, 'st')

我应该得到:

[('01012', 'Victoria St', 'Hotel Grand Pacific'), ('01013', 'Victoria St', "St. Joseph's Ch"), ('01019', 'Victoria St', 'Bras Basah Cplx')]

请帮我检查一下我的代码:

def lookup_bus_stop_by_road_name(bus_stops, name):

    matched = []

    for stops in bus_stops:
        new_name = name.lower()
        if stops[1] == new_name:
            matched.append(stops)
    return matched

3 个回答

1

你应该把你的函数改成这样:

def lookup_bus_stop_by_road_name(bus_stops, name):
    matched = []
    new_name = name.lower()

    for stops in bus_stops:
        if name in stops:
            matched.append(tuple(stops.split(',')))
    return matched
1

s 替换成 open 等等。我用 s 这个字符串只是为了快速演示。

>>> s = '''\
01012,Victoria St,Hotel Grand Pacific
01013,Victoria St,St. Joseph's Ch
01019,Victoria St,Bras Basah Cplx''';
>>> 
>>> lines = s.split('\n');
>>> lines
['01012,Victoria St,Hotel Grand Pacific', "01013,Victoria St,St. Joseph's Ch", '01019,Victoria St,Bras Basah Cplx']
>>> l = [];
>>> for line in lines: l.append(tuple(line.split(',')));

>>> l
[('01012', 'Victoria St', 'Hotel Grand Pacific'), ('01013', 'Victoria St', "St. Joseph's Ch"), ('01019', 'Victoria St', 'Bras Basah Cplx')]
1

一种更简洁(而且符合Python风格)的方法是使用列表推导式,像这样:

def lookup_bus_stop_by_road_name(bus_stops, name):
    return [bus_stop for bus_stop in bus_stops if name.lower() in bus_stop[1].lower()]

撰写回答