gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:17:34 25 4
gpt4 key购买 nike

我正在使用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 列,但我想在用户输入处设置列数,并且无需每次都对其进行硬编码。

我错过了什么?如何让打印件了解我有多少个列表?

所需输出:例如,如果用户将列数设置为 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 更改为你想要的任何数字

关于python - 将未知数量的列表打印为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42320151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com