For example:
list1 = ['abc','def','ghi','jk'`]
output is : list2 = ['adgj','behk','cfi']
Basically each element i
in list2
should be the ith character in each element of list1
.
I know the general format would be something along the lines of creating list2 with the following element until the end of each.
[list1[0][0]
[list1[0][1]
[list1[0][2]
....
However, when I try to create for loops it says that I am out of index and am also struggling with getting the index to stop if the last element in list1 is smaller size than the rest of the elements. I just need some direction on how to set up the for loops?
for I in range(Len(list1)):
list2[I]=list1[I][0]
I know I need a second for loop to change for index 0, having trouble implementing that
You could do something like this:
list1 = ['abc','def','ghi','jk']
max_length = max(map(len, list1))
result = []
for i in range(max_length):
element = []
for s in list1:
element.append(s[i] if i < len(s) else "")
result.append(''.join(element))
print(result)
The outer loop iterates over all the possible indices, the inner loop iterates over the words, the line:
s[i] if i < len(s) else ""
retrieves s[i]
if i is in bounds. Although the most pythonic (as mentioned by @juanpa.arrivillaga) way is to do:
from itertools import zip_longest
list1 = ['abc', 'def', 'ghi', 'jk']
result = list(map(''.join, zip_longest(*list1, fillvalue='')))
print(result)
Output
['adgj', 'behk', 'cfi']
Albeit, the latter is a bit advanced solution.
You can either do this using itertools.zip_longest
as @juanpa.arrivillaga said in the comments:
list(map(''.join, zip_longest(*list1, fillvalue='')))
Or manually:
result = [''] * max(map(len, list1))
for i in range(len(result)):
for s in list1:
if i < len(s): result[i] += s[i]
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.