我有一个数字列表,我希望这个列表可以水平打印。每9个元素应在新行上打印
我的列表每9个元素都会拆分一次,但是我很努力地将其转置
media_list = new_amount_list
nth_item = 9
str_list = [
'{}\t\n'.format(m)
if(((media_list.index(m)+1) % nth_item) == 0)
else
'{}\t'.format(m)
for m in media_list
]
print('\n'.join(str_list))
答案 0 :(得分:2)
这是一种简单的方法,而不是专家的方法。 随机导入 media_list = random.sample(range(100),99) start_index = 0 增量= 1
for i in media_list :
if increment%9 ==0:
print(media_list [start_index:increment])
start_index=increment
increment+=1
输出
[50, 68, 67, 5, 32, 72, 12, 96, 24]
[82, 49, 13, 81, 33, 42, 34, 90, 14]
[84, 83, 98, 61, 94, 53, 66, 80, 9]
[47, 55, 45, 73, 4, 28, 38, 71, 74]
[41, 7, 89, 22, 85, 43, 27, 16, 37]
[1, 75, 76, 78, 56, 8, 26, 44, 54]
[58, 46, 57, 31, 11, 97, 70, 64, 10]
[39, 6, 92, 0, 23, 2, 65, 48, 88]
[59, 69, 60, 19, 86, 15, 52, 99, 20]
[62, 25, 35, 91, 40, 30, 36, 3, 77]
[95, 21, 63, 51, 18, 29, 17, 93, 87]
答案 1 :(得分:0)
my_list = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,7,8,9,0]
n = 9
for lst in [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )] :
print (*lst)
输出
1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
9 0 1 2 3 4 5 6 7
7 8 9 0