假设我有这个星号列表,我说是以这种方式打印:
list = ['* *', '*', '* * *', '* * * * *', '* * * * * *', '* * * *']
for i in list:
print i
所以在这里,输出是:
* *
*
* * *
* * * * *
* * * * * *
* * * *
但我希望输出是垂直的,如下所示:
* * * * * *
* * * * *
* * * *
* * *
* *
*
有关这方面的任何提示吗?我试图概念化如何使用list comprehension或for-loops这样的东西,但是没有把它完全正确。
答案 0 :(得分:7)
myList = ['* *', '*', '* * *', '* * * * *', '* * * * * *', '* * * *']
import itertools
for i in itertools.izip_longest(*myList, fillvalue=" "):
if any(j != " " for j in i):
print " ".join(i)
<强>输出强>
* * * * * *
* * * * *
* * * *
* * *
* *
*
答案 1 :(得分:4)
>>> 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
答案 2 :(得分:4)
如果您不想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))
请注意以下几点:
ell
,因为list
是python中的内置词。zip
,这是一个内置函数,用于“组合”像列表这样的迭代。答案 3 :(得分:1)
对于主要使用基本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
示例输出:
* * * * * *
* * * * *
* * * *
* * *
* *
*
答案 4 :(得分:-5)
string[] myList = null;
myList = {'*', '* *', '* * *', '* * * *', '* * * * *', '* * * * * *'};
for(int i=myList.Length-1; i>=0, i--) {
Console.WriteLine(myList[i].ToString());
}