繁体   English   中英

将未知数量的列表打印为列

[英]Print unknown number of lists as columns

我正在使用Python 3.5.2 ,并且想创建一个用户友好的程序,该程序在某些列中输出一定范围的数字。

#User input
start = 0
until = 50
number_of_columns = 4

#Programmer
#create list of numbers
list_of_stuff = [str(x) for x in range(start,until)]
print("-Created "+str(len(list_of_stuff))+" numbers.")
#calculate the number of numbers per column
stuff_per_column = int(len(list_of_stuff) / number_of_columns)
print("-I must add "+str(stuff_per_column)+" numbers on each column.")
#generate different lists with their numbers
generated_lists = list(zip(*[iter(list_of_stuff)]*stuff_per_column))
print("-Columns are now filled with their numbers.")

直到一切都好,但在这里我被卡住了:

#print lists together as columns
for x,y,z in zip(generated_lists[0],generated_lists[1],generated_lists[2]):
    print(x,y,z)
print("-Done!")

我尝试使用该代码,它可以满足我的要求,因为它涉及对列数进行硬编码。 例如,x,y,z适用于3列,但是我想在User输入中设置列数,而无需每次对其进行硬编码。

我想念什么? 如何使印刷品了解我有多少个列表?

所需的输出:例如,如果用户将列数设置为4,则输出为:

1 6 11 16
2 7 12 17
3 8 13 18
4 9 14 19
5 10 15 20
Etc...

采用:

for t in zip(generated_lists[0],generated_lists[1],generated_lists[2]):
    print(' '.join(str(x) for x in t))

或更简洁地:

for t in zip(*generated_lists[:3]):
    print(' '.join(map(str, t)))

所以您需要将3更改为所需的任何数字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM