Home > Net >  Joining values of a list inside another list into a string
Joining values of a list inside another list into a string

Time:11-15

Im trying to join the letters as a string that's inside the list which is also inside the list. So for example, it looks like this [['a', 'b', 'c'], ['d', 'e', 'f']] however I want the result to look like 'ad be cf' which is basically taking the element that lies in the same position in the list. I know how to join the elements into a list that can look like 'abcdef', however, i don't know which I could add in order to return a string that looks like above. Any advice would be thankful!

string = ''
new_grid = []

for a in grid:
    for b in a:
        string  = b
return string

CodePudding user response:

When you want to transpose lists into columns, you typically reach for zip(). For example:

l = [['a', 'b', 'c'], ['d', 'e', 'f']]

# make a list of columns
substrings = ["".join(sub) for sub in zip(*l)]
#['ad', 'be', 'cf']

print(" ".join(substrings)) 
# alternatively print(*substrings, sep=" ")
# ad be cf

CodePudding user response:

This works:

my_list = [['a', 'b', 'c'], ['d', 'e', 'f']]
sorted_list = [list(pair) for pair in zip(my_list[0], my_list[1])]

for i in range(3):
    string = ''.join(sorted_list[i])
    print(string, end=" ")

First, we are pairing each individual list to its corresponding value using [zip][1], then we are joining it into a string, and printing it out.

This solution may not be the most efficient, but it's simple to understand.

Another quick solution without zip could look like this:

my_list = [['a', 'b', 'c'], ['d', 'e', 'f']]
sorted_list = list(map(lambda a, b: a   b, my_list[0], my_list[1]))
print(" ".join(sorted_list)) 
  • Related