Print two or more outputs from functions side by side in python
本问题已经有最佳答案,请猛点这里访问。
我对Python有点陌生,我想知道如果它是不同函数的一部分,您将如何并行地呈现多个输出。因此,举个简单的例子:
1 2 3 4 5 6 7 8 9 10 11 | def function1(): print("This is") def function2(): print("a line") def main(): function1() function2() main() |
如果我这样做,它将打印:
1 2 | This is a line |
但我如何调整它,使其像这样打印出来:
1 | This is a line |
编辑:我注意到了。结束函数在这里有帮助,但是如果我有一个长长的项目列表呢?在那种情况下似乎不起作用。例如,如果我的两个输出是:
1 2 3 4 | 252 245 246 234 |
和
1 2 3 4 | Bob Dylan Nick Ryan |
我想加入这两个组织,所以会是:
1 2 3 4 | 252 Bob 245 Dylan 246 Nick 234 Ryan |
EDIT: I noticed .end function would help here but what if I had a long list of item? It doesn't appear to work in that scenario.
也许是这样?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | def function1(): print('Work It', end='') yield print('Do It', end='') yield print('Harder', end='') yield print('Faster', end='') yield def function2(): print('Make It', end='') yield print('Makes Us', end='') yield print('Better', end='') yield print('Stronger', end='') yield def main(): generator1, generator2 = function1(), function2() while True: try: next(generator1) print(' ', end='') next(generator2) print() except StopIteration: break if __name__ == '__main__': main() |
产量
1 2 3 4 | Work It Make It Do It Makes Us Harder Better Faster Stronger |
只在函数print end中使用='这样
1 2 3 4 5 6 7 8 9 10 11 | def function1(): print("This is", end="") def function2(): print("a line", end="") def main(): function1() function2() main() |