简体   繁体   English

将Python列表分成5组,然后打印

[英]Splitting a Python list into groups of 5 and then printing

I have a list item that looks like this: 我有一个看起来像这样的清单项目:

dblist=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']

It could have more than 12 items (could be infinite). 它可能有超过12个项目(可以是无限个)。 I want to print this list in groups of five and want my output to look like this: 我想以五个为一组打印此列表,并希望输出如下所示:

env1: one two three four five
env2: six seven eight nine ten
env3: eleven twelve

How can I achieve this? 我该如何实现?

I found some nice tricks that appear to be able to do the job, but I just can't seem to make it work with my code. 我发现了一些不错的技巧似乎可以完成这项工作,但是我似乎无法使其与我的代码一起使用。 For example, the following seems to be able to do what I want: 例如,以下似乎可以执行我想要的操作:

def n_split(iterable, n, fillvalue=None):
    num_extra = len(iterable) % n
    zipped = zip(*[iter(iterable)] * n)
    return zipped if not num_extra else zipped + [iterable[-num_extra:], ]

for ints in n_split(range(1,32), 5):
    print(([str(i) for i in ints]))

Has the output of: 具有以下输出:

['1', '2', '3', '4', '5']
['6', '7', '8', '9', '10']
['11', '12', '13', '14', '15']
['16', '17', '18', '19', '20']
['21', '22', '23', '24', '25']
['26', '27', '28', '29', '30']
['31', '32', '33']

How can I use this technique to print dblist in groups of five as shown in the beginning? 如开头所示,如何使用这种技术以五个为一组打印dblist?

Use str.join() : 使用str.join()

for group in n_split(dblist, 5):
    print ' '.join(group)

You could add enumerate() to add a counter: 您可以添加enumerate()以添加一个计数器:

for count, group in enumerate(n_split(dblist, 5), 1):
    print 'env{}: {}'.format(count, ' '.join(group))

Demo: 演示:

>>> def n_split(iterable, n, fillvalue=None):
...     num_extra = len(iterable) % n
...     zipped = zip(*[iter(iterable)] * n)
...     return zipped if not num_extra else zipped + [iterable[-num_extra:], ]
... 
>>> dblist=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']
>>> for group in n_split(dblist, 5):
...     print ' '.join(group)
... 
one two three four five
six seven eight nine ten
eleven twelve
>>> for count, group in enumerate(n_split(dblist, 5), 1):
...     print 'env{}: {}'.format(count, ' '.join(group))
... 
env1: one two three four five
env2: six seven eight nine ten
env3: eleven twelve

Is this what you want? 这是你想要的吗?

dblist=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']
for i in range(0,len(dblist),5):
    print(dblist[i:i+5])

['one', 'two', 'three', 'four', 'five']
['six', 'seven', 'eight', 'nine', 'ten']
['eleven', 'twelve']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM