1

I have list of lists of strings like this:

[['today'], ['is'], ['rainy'], ['day']]

I want to print each word vertically in python. I want to output something like this

t i r d
o s a a
d   i y
a   n  
y   y  
3
  • 1
    You need to provide more detail. Ideally you want to show the code of your attempt implementing the algorithm, where and why you think it fails, etc. Commented Feb 10, 2021 at 8:30
  • Is the list over each string intentional?. you have a list of list, where each list contains a string Commented Feb 10, 2021 at 8:36
  • yes I have a list of lists of strings contain a string, but it can be converted back to a normal list of string @RishabhKumar Commented Feb 10, 2021 at 9:02

3 Answers 3

3

You could try itertools.zip_longest

from itertools import zip_longest
lst = [['today'], ['is'], ['rainy'], ['day']]
print('\n'.join([' '.join([y or ' ' for y in x]) for x in zip_longest(*[i[0] for i in lst])]))

Output:

t i r d
o s a a
d   i y
a   n  
y   y  
Sign up to request clarification or add additional context in comments.

1 Comment

In this case I'd use y or ' ' instead of ' ' if y is None else y
1

You can do this will a loop.

l =  [['today'], ['is'], ['rainy'], ['day']]

max_len = len(max(l, key=lambda x: len(x[0]))[0])
out = ''

for idx in range(max_len):
    for item in l:
        small_item = item[0]
        if len(small_item) > idx:
            out += small_item[idx]
            out += "\t"
        else:
            out += " \t"
    out += "\n"

print(out)

t   i   r   d   
o   s   a   a   
d       i   y   
a       n       
y       y    

Idea behind this is simple. You have to find the length of longest string you have. Then basically you want to pick up each item from each string if that element is valid, else add a empty space. Add tabs and newlines to format as you want.

Comments

0
lst = [['today'], ['is'], ['rainy'], ['day']]
max_len = len(max(lst, key=lambda x: len(x[0]))[0])

for i in range(max_len):
    for word in lst:
        try:
            print(word[0][i], end=' ')
        except IndexError:
            print(' ', end=' ')
    print()

Output:

t i r d 
o s a a
d   i y
a   n
y   y

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.