如何在 Python 语音识别中将不断变化的列表合并为一个列表?
How to merge mutating numbers of lists into one in Python Speech Recognition?
我想将可变列表合并为一个。我正在使用语音识别,所以我得到的单词列表一直在变化。有人说用 + 运算符添加列表,但是每次说话者说话时,都会生成各种数量的列表。就好像程序不知道每次会有多少个列表一样。我有 ['hi'] 和 ['hello'] 等列表,下次我有 ['one']、['two'] 和 ['three'].我想编写一个代码或一个函数,允许将所有数量的列表添加到一个列表中。因此,我想对所有数量的列表实施 same 代码。最后我想要 ['hi'、'hello'] 或 ['one'、'two'、'three']。我对 Python 很陌生。提前致谢!
您有三种合并列表的方法:
# using +
a = ['A']
b = [1, 2]
a + b # ['A', 1, 2]
# using append
a.append(b) # ['A', [1, 2]]
# using extend
a.extend(b) # ['A', 1, 2]
它们有什么区别?
+
运算符创建新列表,而方法会改变您调用它们的列表。
我相信 +
运算符正是您想要的。例如:
a = ["foo", "bar"]
b = ["bar", "got"]
c = a + b
打印['foo', 'bar', 'bar', 'got']
如果要将 b
添加到 a
,请使用 .extend()
。你也可以使用 +=
但它可以说不是 pythonic。
a = ["foo", "bar"]
b = ["bar", "got"]
a.extend(b) # (or a += b)
print(a)
打印["foo", "bar", "bar", "got"]
更新:根据作者的新信息,这是我的四行解决方案:
def merge(lists):
result = []
for list in lists:
result.extend(list)
return result
或者,使用 functools.reduce()
和 operator
模块:
import functools, operator
def merge(lists):
return functools.reduce(operator.add, lists)
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.
和operator.add()
是lambda x, y: x + y
的快捷方式。
我想将可变列表合并为一个。我正在使用语音识别,所以我得到的单词列表一直在变化。有人说用 + 运算符添加列表,但是每次说话者说话时,都会生成各种数量的列表。就好像程序不知道每次会有多少个列表一样。我有 ['hi'] 和 ['hello'] 等列表,下次我有 ['one']、['two'] 和 ['three'].我想编写一个代码或一个函数,允许将所有数量的列表添加到一个列表中。因此,我想对所有数量的列表实施 same 代码。最后我想要 ['hi'、'hello'] 或 ['one'、'two'、'three']。我对 Python 很陌生。提前致谢!
您有三种合并列表的方法:
# using +
a = ['A']
b = [1, 2]
a + b # ['A', 1, 2]
# using append
a.append(b) # ['A', [1, 2]]
# using extend
a.extend(b) # ['A', 1, 2]
它们有什么区别?
+
运算符创建新列表,而方法会改变您调用它们的列表。
我相信 +
运算符正是您想要的。例如:
a = ["foo", "bar"]
b = ["bar", "got"]
c = a + b
打印['foo', 'bar', 'bar', 'got']
如果要将 b
添加到 a
,请使用 .extend()
。你也可以使用 +=
但它可以说不是 pythonic。
a = ["foo", "bar"]
b = ["bar", "got"]
a.extend(b) # (or a += b)
print(a)
打印["foo", "bar", "bar", "got"]
更新:根据作者的新信息,这是我的四行解决方案:
def merge(lists):
result = []
for list in lists:
result.extend(list)
return result
或者,使用 functools.reduce()
和 operator
模块:
import functools, operator
def merge(lists):
return functools.reduce(operator.add, lists)
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.
和operator.add()
是lambda x, y: x + y
的快捷方式。