2

我正在为 CS 类编写程序,需要一些 python 3 编码的帮助。这是我当前编写的代码:

def main():
    print() # blank line
    phrase = input("Please enter a phrase: ")
    wordlist = phrase.split()
    print("Original text:",phrase)
    for msg in wordlist:
        print(msg)

输出:

    Phil
    likes
    to
    code

我不能使用任何进口或类似的东西。我只能使用像循环或切片或拆分这样的小东西。任何帮助,将不胜感激。我需要输出看起来像:

P l t c
h i o o
i k   d
l e   e
  s
4

2 回答 2

1

您可以使用itertools.zip_longest()与 fillvalue 作为空间。例子 -

>>> s = "Four score and seven years ago"
>>> ls = s.split()
>>> import itertools
>>> for i in itertools.zip_longest(*ls,fillvalue=' '):
...     print(*i)
...
F s a s y a
o c n e e g
u o d v a o
r r   e r
  e   n s

itertools.izip_longest对于 Python 2 。

于 2015-09-29T04:13:03.450 回答
0

如您所问,没有进口:

words = phrase.split()
height = max(map(len, words))
padded = [word.ljust(height) for word in words]
for row in zip(*padded):
    print(' '.join(row))

我希望你没问题。

于 2015-09-29T08:30:20.147 回答