[英]Is there a way to print a list that moves to a new line after specific items in the list?
[英]Idiomatic way to print arbitrary number of items from a list on each line
我想從列表中打印數據,例如:
['0.10', '0.15', '-0.25', '0.30', '1.50', '1.70']
但是,與其使用類似的方法打印列表中的一個元素:
for item in list:
print item
我想從每一行的列表中打印任意數量的項目。 我可以想到許多麻煩的方法,並且在文檔的itertools頁面上看到了使用石斑魚配方的答案。 我很高興使用它,但是我懷疑可能會有更好的方法。
我可能想要的示例輸出是:
0.10 0.15 -0.25
0.30 1.50 1.70
要么:
0.10 0.15 -0.25 0.30
1.50 1.70
因此,每行上的項目數不一定是列表上項目數的一個因素。 如果列表太短,則某些行可能以較少的元素結尾。
這可行。 看起來很簡單。
for i in range(0, len(some_list), line_length):
print( some_list[i:i+line_length] )
如果要在問題中顯示文字格式,則必須執行類似的操作。
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] ) )
另一個(也許)更簡單的版本:
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
產生:
0.10 0.15 -0.25
0.30 1.50 1.70
認為此解決方案更加清晰:
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)
希望這對您有所幫助:)
PS:實際上,一種僅打印的解決方案在包含許多變量的列表中可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.