How do I print this list vertically?

后端 未结 5 1493
猫巷女王i
猫巷女王i 2020-12-11 19:21

Let\'s say I have this list of asterisks, and I say it to print this way:

list = [\'* *\', \'*\', \'* * *\', \'* * * * *\', \'* * * * * *\', \'* * * *\']
for         


        
5条回答
  •  长情又很酷
    2020-12-11 19:56

    If you don't want to import itertools, you can do it like this:

    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:

    1. I have renamed the list to ell, since list is a built-in word in python.
    2. This works by expanding the strings so that they all have the same length by padding them with spaces, then converting the list of strings into a list of lists representing a rectangular matrix.
    3. I have used the trick described in this post to do a matrix transpose, which is what you want to print. It uses zip, which is a builtin function for "combining" iterables like lists.
    4. I also used a couple of comprehensions to keep things short.
    5. This works in python 2 and 3. If you want it to look more like python 2, take out the parentheses used for the print function.

提交回复
热议问题