[英]How do I print this list vertically?
Let's say I have this list of asterisks, and I say it to print this way: 假设我有这个星号列表,我说它以这种方式打印:
list = ['* *', '*', '* * *', '* * * * *', '* * * * * *', '* * * *']
for i in list:
print i
So here, the output is: 所以在这里,输出是:
* *
*
* * *
* * * * *
* * * * * *
* * * *
But I want the output to be vertical, like this: 但我希望输出是垂直的,如下所示:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Any tips on doing this? 这样做的任何提示? I've tried to conceptualize how to use things like list comprehension or for-loops for this, but haven't got it quite right.
我试图概念化如何使用list comprehension或for-loops这样的东西,但是没有把它弄得很正确。
myList = ['* *', '*', '* * *', '* * * * *', '* * * * * *', '* * * *']
import itertools
for i in itertools.izip_longest(*myList, fillvalue=" "):
if any(j != " " for j in i):
print " ".join(i)
Output 产量
* * * * * *
* * * * *
* * * *
* * *
* *
*
>>> from itertools import izip_longest
>>> list_ = ['a', 'bc', 'def']
>>> for x in izip_longest(*list_, fillvalue=' '):
... print ' '.join(x)
...
a b d
c e
f
If you don't want to import itertools
, you can do it like this: 如果您不想
import itertools
,可以这样做:
ell = ['* *', '*', '* * *', '* * * * *', '* * * * * *', '* * * *']
unpadded_ell = [s.replace(' ', '') for s in ell]
height = len(max(unpadded_ell))
for s in zip(*(s.ljust(height) for s in unpadded_ell)):
print(' '.join(s))
Note a couple of things: 请注意以下几点:
ell
, since list
is a built-in word in python. ell
,因为list
是python中的内置单词。 zip
, which is a builtin function for "combining" iterables like lists. zip
,这是一个内置函数,用于“组合”列表之类的迭代。 How about this, for a version that mostly uses basic Python operations: 对于主要使用基本Python操作的版本,这个怎么样:
data = ['* *', '*', '* * *', '* * * * *', '* * * * * *', '* * * *']
max_len = max(len(x) for x in data) # find the longest string
for i in range(0, max_len, 2): # iterate on even numbered indexes (to get the *'s)
for column in data: # iterate over the list of strings
if i < len(column):
print column[i], # the comma means no newline will be printed
else:
print " ", # put spaces in for missing values
print # print a newline at the end of each row
Example output: 示例输出:
* * * * * *
* * * * *
* * * *
* * *
* *
*
string[] myList = null;
myList = {'*', '* *', '* * *', '* * * *', '* * * * *', '* * * * * *'};
for(int i=myList.Length-1; i>=0, i--) {
Console.WriteLine(myList[i].ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.