vick vick - 4 months ago 16
Python Question

How to merge mutating numbers of lists into one in Python Speech Recognition?

I want to merge mutable lists into one. I am using speech recognition, so the lists of words that I am getting are changing all the time. Some people said to add lists using the + operator, but every time the speaker speaks, various numbers of lists are generated. Think as if the program doesn't already know how many lists there will be every time. I have lists such as ['hi'] and ['hello'] and the next time I have lists such as ['one'], ['two'] and ['three']. I want to write a code or a function that allows to add all numbers of lists into one. Thus, I want to implement the same code to all numbers of lists. In the end I want to have ['hi', 'hello'] or ['one', 'two', 'three']. I am very new to Python. Thank you in advance!

Answer

I believe the + operator is exactly what you want. For example:

a = ["foo", "bar"] 
b = ["bar", "got"]
c = a + b

prints ['foo', 'bar', 'bar', 'got']


If you want to add b to a use .extend(). You could also use += but it's arguably less pythonic.

a = ["foo", "bar"]
b = ["bar", "got"]
a.extend(b)  # (or a += b)
print(a)

prints ["foo", "bar", "bar", "got"]

UPDATED: With new information from the author, here's my four-line solution:

def merge(lists):
    result = []
    for list in lists:
        result.extend(list)
    return result

or, alternatively using functools.reduce() and the operator module:

import functools, operator
def merge(lists):
    return functools.reduce(operator.add, lists)

functools.reduce() simply does:

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence.

and operator.add() is a shortcut for lambda x, y: x + y.

Comments