如何从列表中每行显示5个数字?
lx = [1,2,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
def display(lx):
for i in range(0,len(lx), 5):
x = lx[i:i +5]
return x
print(display(lx))
我当前的代码仅显示一行包含5个数字的行,并且预期应为5行,每行包含5个数字
答案 0 :(得分:6)
您可以通过使函数产生切片列表来使该函数成为生成器:
def display(lx):
for i in range(0, len(lx), 5):
yield lx[i:i + 5]
print(*display(lx), sep='\n')
这将输出:
[1, 2, 4, 5, 6]
[7, 8, 9, 10, 11]
[12, 13, 14, 15, 16]
[17, 18, 19, 20, 21]
[22, 23, 24, 25]
答案 1 :(得分:1)
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
def printer(lis, num_per_line):
z = 1
for each_num in lis:
if z%(num_per_line) == 0:
print(each_num, end='\n')
else:
print(each_num, end='\t')
z+=1
printer(x, 5)
在需要传递列表和实体以单行打印的地方使用此功能。
输出为:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
答案 2 :(得分:1)
lst = [55, 26, 59, 35, 28, 22, 33, 43, 49, 45, 20, 11, 34, 44, 57, 12, 16, 31, 32, 58, 15, 38, 37, 48, 39]
def display(lst):
x = 0
while x in range(len(lst)):
print(lst[x:x+5])
x+=5
#Output
[55, 26, 59, 35, 28]
[22, 33, 43, 49, 45]
[20, 11, 34, 44, 57]
[12, 16, 31, 32, 58]
[15, 38, 37, 48, 39]
答案 3 :(得分:0)
可以使用不同的方法来解决此问题:
x=[] #your given list
for t in range(len(x)):
if(t%5==0):
print('\n')
print(str(x[t])+'\t',end='') #end will print numbers on same line otherwise
此代码将提供所需的输出。