0

I have a list of lists which I want to flatten while inserting an item in between them. My original list is in the form:

l = [["a","b"],["c"],["d"]]

What I want is, to flatten the list and separate them with a character

n = ["a","b",".","c",".","d"]

Flattening lists should be possible on with list comprehension as mentioned in many SO answers:

flat_list = [item for sublist in l for item in sublist]

but is it possible to flatten the list with a character/string of my choosing?

It could be done with by appending . to each list except the last one. But is there something more elegant like .join?

2 Answers2

5

One way I can think of is to extend the sublist on the second level of iteration by adding the separator:

[j for i in l for j in [*i, '.']][:-1]
# ['a', 'b', '.', 'c', '.', 'd']
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
yatu
  • 86,083
  • 12
  • 84
  • 139
1

As pointed by @Kurtis use this only if you have characters in the lists.

mylist = [["a", "b"], ["c"], ["d"]]

print(list(".".join(map("".join, mylist))))

# ['a', 'b', '.', 'c', '.', 'd']

UPDATE:

There are multiple ways to do this, I'll mention a few.

For a given mylist

mylist = [["asd", "b"], ["csd"], ["d"]]

Method 1: Using reduce

from functools import reduce
print(reduce(lambda a, b: a+["."]+b, mylist))

Method 2:

print([item for sublist in mylist for item in sublist+["."]][:-1])

Method 3: Same as Method 2

flat_list = []
[flat_list.extend(sublist + ["."]) for sublist in mylist][:-1]
print(flat_list)

Method 4: If you can afford two separators then split with the other

print("~.~".join(map("~".join, mylist)).split("~"))
kartoon
  • 1,040
  • 1
  • 11
  • 24
  • Note that this solution is only correct if each individual string is a single character as it relies on the implicit splitting of strings into individual characters when the string is used as an iterable. This is not a general solution to the problem. The solution by @yatu is better. – Kurtis Rader Apr 24 '20 at 02:00