简体   繁体   English

惯用的方式从每行的列表中打印任意数量的项目

[英]Idiomatic way to print arbitrary number of items from a list on each line

I want to print data from a list, such as: 我想从列表中打印数据,例如:

['0.10', '0.15', '-0.25', '0.30', '1.50', '1.70']

However, rather than printing one element in the list using something like: 但是,与其使用类似的方法打印列表中的一个元素:

for item in list:
    print item

I want to print an arbitrary number of items from the list on each line. 我想从每一行的列表中打印任意数量的项目。 I can think of many messy ways to do it and I saw an answer which used the grouper recipe from the itertools page on the docs. 我可以想到许多麻烦的方法,并且在文档的itertools页面上看到了使用石斑鱼配方的答案。 I'm happy to use that, but I suspect there might be a better way of doing it. 我很高兴使用它,但是我怀疑可能会有更好的方法。

An example output I might like would be: 我可能想要的示例输出是:

0.10   0.15  -0.25
0.30   1.50   1.70

Or: 要么:

0.10   0.15  -0.25   0.30
1.50   1.70

So the number of items on each line isn't necessarily a factor of the number of items on the list. 因此,每行上的项目数不一定是列表上项目数的一个因素。 Some lines may end with fewer elements if the list is too short. 如果列表太短,则某些行可能以较少的元素结尾。

This works. 这可行。 It seems pretty simple. 看起来很简单。

for i in range(0, len(some_list), line_length):
    print( some_list[i:i+line_length] )

If you want the literal formatting shown in the question, you'd have to do something like this. 如果要在问题中显示文字格式,则必须执行类似的操作。

for i in range(0, len(some_list), line_length):
    print( "  ".join( "{0:.2f}".format(x) for x in some_list[i:i+line_length] ) )

Another still (maybe) simpler version: 另一个(也许)更简单的版本:

mylist = ['0.10', '0.15', '-0.25', '0.30', '1.50', '1.70']
line_items = 3

for n, item in enumerate(mylist):
    if (n+1) % line_items:
        print item,
    else:
        print item

produces: 产生:

0.10 0.15 -0.25
0.30 1.50 1.70

Think this solution is a little bit more clear: 认为此解决方案更加清晰:

a = ['0.10', '0.15', '-0.25', '0.30', '1.50', '1.70']
body = []
length = 2
for b in xrange(len(a)):
    body.append(str(a[b]))
    if b % length:
        body.append("\n")
    else:
        body.append("\t")
print "".join(body)

Hope this one helps :) 希望这对您有所帮助:)

PS: And actually a one print only solution might be helpful in lists containing many variables. PS:实际上,一种仅打印的解决方案在包含许多变量的列表中可能会有所帮助。

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

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