[英]Concatenating strings more efficiently in Python
我学习Python已有几个月,并且想了解一种编写此函数的更简洁有效的方法。 我只是想查询附近的公交车时间,然后在LCD上显示mtodisplay的内容,这只是一件基本的事情,但是我不确定mtodisplay = mtodisplay + ...行。 必须有一种更好,更智能,更Pythonic的字符串连接方式,而无需诉诸列表(我想将此字符串直接输出到LCD。节省我的时间。也许那是我的问题……我正在使用快捷方式)。
同样,我使用countit和thebuslen的方法似乎有点荒谬! 我真的很欢迎提出一些建议或建议以使它变得更好。 只是想学习!
谢谢
json_string = requests.get(busurl)
the_data = json_string.json()
mtodisplay='220 buses:\n'
countit=0
for entry in the_data['departures']:
for thebuses in the_data['departures'][entry]:
if thebuses['line'] == '220':
thebuslen=len(the_data['departures'][entry])
print 'buslen',thebuslen
countit += 1
mtodisplay=mtodisplay+thebuses['expected_departure_time']
if countit != thebuslen:
mtodisplay=mtodisplay+','
return mtodisplay
我不确定“重新排序到列表”是什么意思,但是类似以下内容:
json_string = requests.get(busurl)
the_data = json_string.json()
mtodisplay= []
for entry in the_data['departures']:
for thebuses in the_data['departures'][entry]:
if thebuses['line'] == '220':
thebuslen=len(the_data['departures'][entry])
print 'buslen',thebuslen
mtodisplay.append(thebuses['expected_departure_time'])
return '220 buses:\n' + ", ".join(mtodisplay)
像这样串联字符串
mtodisplay = mtodisplay + thebuses['expected_departure_time']
过去效率很低,但是很长一段时间以来,Python确实会重用被链接的字符串(只要没有其他引用),因此它是线性性能,而不是必须避免的旧式二次性能。
在这种情况下,您似乎已经有了要在其间放入逗号的项目列表,因此
','.join(some_list)
可能更合适(并且自动表示您最后没有多余的逗号)。
因此,下一个问题是构造列表(也可以是生成器等)。 @bgporter显示了如何制作列表,所以我将显示生成器版本
def mtodisplay(busurl):
json_string = requests.get(busurl)
the_data = json_string.json()
for entry in the_data['departures']:
for thebuses in the_data['departures'][entry]:
if thebuses['line'] == '220':
thebuslen=len(the_data['departures'][entry])
print 'buslen',thebuslen
yield thebuses['expected_departure_time']
# This is where you would normally just call the function
result = '220 buses:\n' + ','.join(mtodisplay(busurl))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.