我已经学习 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
请您参考如下方法:
像这样连接字符串
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))
