如何使用%打印一个大的数字列表?

2024-09-28 22:51:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个格式,我需要遵守其他打印号码列表(该列表有200多个号码):

my_format = '%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d%6d\n'
my_list = [1,2,3,4,5,6,199, 57, .........]

基本上,它只是%6d重复15次

使用%格式化字符串时,我知道需要执行以下操作:

with open('my_out.txt', 'w') as fout:
    fout.write(my_format % (num1, num2, num3, num4, num5, ....., num15)

在我的情况下,我需要将我的_列表分成15个部分,在最后一个部分中,我可能没有15个数字;因此,我需要以某种方式忽略变量num,因为我已经遍历了所有的数字,所以它在我的_列表中没有任何项。另外,考虑到我需要创建15个变量(从num1到num15),因此我可以使用:

my_format % (num1, num2, num3, num4, num5, ....., num15)

我的文件应如下所示:

0112345678911121

145897589765430

346718

有没有一种聪明有效的方法可以解决我的问题


Tags: 字符串format列表my格式数字list号码
3条回答

只需使用%6d格式化各个项目,然后在空字符串上连接它们,并在末尾添加换行符:

nums = list(range(15))
formatted = "".join("%6d" % n for n in nums) + "\n"

print(formatted)
#      0     1     2     3     4     5     6     7     8     9    10    11    12    13    14

这不是一种聪明的(甚至是Python式的)方式,但它可以完成任务:

with open('my_out.txt', 'w') as fout:
    while len(my_list) > 0:
        str = ''
        for loop in range(0, 15):
            try:
                str += '%6d' % my_list.pop(0)
            except:
                break
        str += '\n'
        fout.write(str)
def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

list_chunks = list(chunks(my_list, 15))

all_item = []
for element in x:
    formatted = "".join("%6d" % n for n in element) + "\n"
    all_item.append(formatted)

您可以将其作为列表或直接打印到文件中

该解决方案由@Aplet123提供。我只是把所有的东西放在一起

相关问题 更多 >