[英]How do I get a second element in a list and append it to different list
[英]how to get the second word of an element in a list
给定输入字符串,搜索存储所有公共汽车站数据的元组列表,并返回包含具有匹配字符串的道路的元组列表。 大写和小写被认为是相同的。 如果未找到匹配项,请返回空列表。
假设已经提供了公共汽车站数据,即已经评估了以下语句:
bus_stops = read_data('bus_stops.txt')
我得到了
bus_stops.txt
01012,维多利亚街,太平洋大酒店01013,Victoria St,St。 约瑟夫的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
用open
等替换s
..我用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')]
你应该改变你的功能
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
更短(和Pythonic)的方式是使用这样的列表推导:
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()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.