Dr. Andrew
Dr. Andrew

Reputation: 2621

Joining Lists of Lists of Strings

I've a list of lists, in which each element is a single character:

 ngrams = [['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'],
 ['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']]

From this, I want to generate a new single list with the content ['aa','ab','ac','ba','bb','bc','ca','cb','cc']. The individual elements of each list are appended to each other but in reverse order of the lists. I've come up with this (where np = 2):

for cnt in range(np-2,-1,-1):
  thisngrams[-1] = [a+b for (a,b) in zip(thisngrams[-1],thisngrams[cnt])]          

My solution needs to handle np higher than just 2. I expect this is O(np), which isn't bad. Can someone suggest a more efficient and pythonic way to do what I want (or is this a good pythonic approach)?

Upvotes: 1

Views: 86

Answers (1)

Ajax1234
Ajax1234

Reputation: 71471

You can try this:

ngrams = [['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'],
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']]

new = map(''.join, zip(*ngrams))

Output:

['aa', 'ba', 'ca', 'ab', 'bb', 'cb', 'ac', 'bc', 'cc']

For more than two elements:

n = [["a", "b", "c"], ["a", "c", "d"], ["e", "f", "g"]]

new = map(''.join, zip(* reversed(ngrams)))

#in Python3
#new = list(map(''.join, zip(* reversed(ngrams))))

Output:

['eaa', 'fcb', 'gdc']

Upvotes: 5

Related Questions