将end='' 添加到您的第一个打印语句应该可以解决问题。通过指定结束字符为空字符串,您将覆盖默认的\n 字符(默认情况下打印语句以换行符结尾)。
for store, data in results.items():
print('Store: {}'.format(store), end='')
if data:
for location in data:
print(location)
我们只会在第一个打印语句中添加end='',因为我们希望在您打印出位置后打印新行。
如果您想用, 分隔打印,当然您只需将+ ',' 添加到您的第一个打印语句即可。
如果您使用的是 Python 3,这将立即生效。如果您使用的是 Python 2.X,则必须将此行添加到文件顶部:from __future__ import print_function
下面是一个简单的例子:
from __future__ import print_function
l1 = ['hello1', 'hello2', 'hello3']
l2 = ['world1', 'world2', 'world3']
for i,j in zip(l1, l2):
print (i, end='')
print (j)
Output:
hello1world1
hello2world2
hello3world3
如果我们采用相同的代码,但稍作改动并删除end='',就会发生这种情况:
from __future__ import print_function
l1 = ['hello1', 'hello2', 'hello3']
l2 = ['world1', 'world2', 'world3']
for i,j in zip(l1, l2):
print (i)
print (j)
Output:
hello1
world1
hello2
world2
hello3
world3
如您所见,每一行都以换行符结尾,这将为每个语句打印一个新行。