A list of strings is given to me and I have to print their elements in a specific manner.
suppose, L = ['RED', 'GREEN', 'BLUE']
and the output is supposed to be, RGBERLDEUEEN
A simple for loop will do the job.
L = ['RED', 'GREEN', 'BLUE']
s = ''
for i in range(max([len(x) for x in L])): #len of longest word in L
for item in L:
try:
s += item[i] + ' '
except IndexError:
pass
print(s)
R G B E R L D E U E E N
This uses some advanced concepts, but it's neat and tidy:
from itertools import zip_longest, chain
L = ['RED', 'GREEN', 'BLUE']
print(''.join(chain(*zip_longest(*L, fillvalue=''))))
# 'RGBERLDEUEEN'
To include spaces between the letters, you can do this instead:
' '.join(''.join(chain(*zip_longest(*L, fillvalue=''))))
# R G B E R L D E U E E N
Another solution using itertools
:
from itertools import chain, zip_longest
l = ['RED', 'GREEN', 'BLUE']
print(*filter(bool, chain(*zip_longest(*l))))
This can probably be done with a nested while-for loop. Something like
length_of_longest_string = 0
for s in L:
length_of_longest_string = max(len(s), length_of_longest_string)
i = 0
result_string = ""
while i < length_of_longest_string:
for s in L:
if i >= len(s):
continue
else:
result_string += s[i] + " "
i += 1
print(result_string)
where you just find the length of the longest string using the initial for loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.