Python在同一行上打印
我遇到的问题是在同一行上打印phone_sorter()和number_calls()。例如,它将打印电话分拣机的两行,但电话号码将打印在它的正下方。我尝试了end=''方法,但似乎不起作用Python在同一行上打印,python,printing,formatting,Python,Printing,Formatting,我遇到的问题是在同一行上打印phone_sorter()和number_calls()。例如,它将打印电话分拣机的两行,但电话号码将打印在它的正下方。我尝试了end=''方法,但似乎不起作用 customers=open('customers.txt','r') calls=open('calls.txt.','r') def main(): print("+--------------+------------------------------+---+---------+----
customers=open('customers.txt','r')
calls=open('calls.txt.','r')
def main():
print("+--------------+------------------------------+---+---------+--------+")
print("| Phone number | Name | # |Duration | Due |")
print("+--------------+------------------------------+---+---------+--------+")
print(phone_sorter(), number_calls())
def time(x):
m, s = divmod(seconds, x)
h, m = divmod(m, x)
return "%d:%02d:%02d" % (h, m, s)
def phone_sorter():
sorted_no={}
for line in customers:
rows=line.split(";")
sorted_no[rows[1]]=rows[0]
for value in sorted(sorted_no.values()):
for key in sorted_no.keys():
if sorted_no[key] == value:
print(sorted_no[key],key)
def number_calls():
no_calls={}
for line in calls:
rows=line.split(";")
if rows[1] not in no_calls:
no_calls[rows[1]]=1
else:
no_calls[rows[1]]+=1
s={}
s=sorted(no_calls.keys())
for key in s:
print(no_calls[key])
main()
您的关键问题是
phone\u sorter
和number\u calls
都自己打印,并且返回None
。因此,打印它们的返回值是荒谬的,在它们完成所有单独的行打印之后,应该以一行毫无意义的None
结束
更好的方法是将它们重新构造为返回,而不是打印,它们确定的字符串,然后在“编排”主
函数中安排打印格式正确的字符串
看起来他们每个人都会返回一个字符串的列表
(他们现在打印在单独的行上),如果这些列表是按相应的顺序排列的,您可能会想要zip
这些列表来准备打印
但是您的代码有点不透明,因此很难判断这两个顺序是否确实对应。他们最好是,如果最后的印刷是有意义的
补充:让我举例说明一下phone\u sorter
中的一些细微改进和一个重大变化:
def phone_sorter():
sorted_no={}
for line in customers:
rows=line.split(";")
sorted_no[rows[1]]=rows[0]
sorted_keys = sorted(sorted_no, key=sorted_no.get)
results = [(sorted_no[k], k) for k in sorted_keys]
return results
明白了吗?除了更好地进行计算外,核心思想是组合一个列表并返回它--main
的工作是适当地格式化和打印它,与number\u calls
返回的类似列表相一致(这似乎是并行的)
现在,这两个列表之间的关系对我来说并不明显,但是,假设它们是并行的,main
可以执行以下操作:
nc = no_calls()
ps = phone_sorter()
for (duration, name), numcalls in zip(ps, nc):
print(...however you want to format the fields here...)
您在main
中打印的标题不会告诉我每个标题下应该打印哪些数据,以及打印的格式(宽度)
例如,每个字段)。但是,main
,并且只有main
,应该是
熟悉并控制这些表示问题,而其他功能则处理适当提取数据的“业务逻辑”。“关注点分离”——编程中的一个大问题 在Python2.7中,您只需要以逗号结尾print'output',
这是python3,我已经试过逗号方法了。@Kirill你在哪里使用end='''
?如果print'output',end=“”)
没有这样做,我不知道该告诉你什么。在上次打印的phone_sorter和number_calls中,它不起作用,所以我只是删除了它。是的,它们都应该打印在同一行上,一行电话号码、姓名等等。我尝试返回,但它只打印函数的一个实例,而不是完整的字典。@Kirill,返回一个列表,正如我提到的;然后在main
中循环这些列表(可能是zip
ped),边打印边打印(如果所有列表都需要在一行上,则最有可能是end='
)。
nc = no_calls()
ps = phone_sorter()
for (duration, name), numcalls in zip(ps, nc):
print(...however you want to format the fields here...)