以可测试代码重新发布为例。
大家好。你们可以帮助我解决这个问题吗?我一直在尝试获取for循环的输出并使用它来打印摘要页面。我希望for循环中的每个迭代都是最后一次迭代旁边的一列。你能帮忙实现这个吗?非常感谢您的帮助。
导入时间,re,集合,运算符
output_list = [['2016-07-12', 'Magazine', 'News Paper #2', 'Podcast', '1234567', '10-10-10-10', 'ABCDEFG', 'Zoo'],
['2016-07-12', 'Book', 'News Paper #2', 'Podcast', '1234567', '10-10-10-10', 'ABCDEFG', 'Zoo']]
def count_types():
item_1 = mm_counts(1)
item_2 = mm_counts(4)
item_3 = mm_counts(3)
def mm_counts(a):
r = []
for i in output_list:
x = (i[a])
#x = (i[0] + ': ' + i[a])
r.append(x)
y = collections.Counter(r)
#test_list = []
for k, v in sorted(y.items(), key=operator.itemgetter(1), reverse=True):
z = (str(k).ljust(5, ' ') + ' ' + (str(v).ljust(5, ' ')))
print(z) #<--- I want to print this column and iterate next columns next to each other.
count_types()
当前输出:
Magazine 1
Book 1
1234567 2
Podcast 2
期望的输出:
Magazine 1 1234567 2
Book 1 Podcast 2
答案 0 :(得分:0)
选择所需的列数,在每行上打印一行后打印一行,每次为每行打印所需数量的元素时,转到下一行。
如果您的目标是拥有两列,请将desiredColumns设置为两列。如果您的目标是两行,请将desiredColumns设置为您要打印的事物总数除以2,然后向上舍入。
import time, re, collections, operator
output_list = [
['2016-07-12', 'Magazine', 'News Paper #2', 'Podcast', '1234567', '10-10-10-10', 'ABCDEFG', 'Zoo'],
['2016-07-12', 'Book', 'News Paper #2', 'Podcast', '1234567', '10-10-10-10', 'ABCDEFG', 'Zoo']]
def count_types():
item_1 = mm_counts(1)
item_2 = mm_counts(4)
item_2 = mm_counts(3)
def mm_counts(a):
r = []
for i in output_list:
x = (i[a])
#x = (i[0] + ': ' + i[a])
r.append(x)
y = collections.Counter(r)
test_list = []
wordsInColumn = 0
desiredColumns = 2
for k, v in sorted(y.items(), key=operator.itemgetter(1), reverse=True):
z = (str(k).ljust(5, ' ') + ' ' + (str(v).ljust(5, ' ')))
print (z, end = '\t')
wordsInColumn += 1
if wordsInColumn % desiredColumns == 0:
print('')
count_types()
# output:
# Magazine 1 Book 1
# 1234567 2 Podcast 2