我是编程新手,需要一些帮助。 我有这样如何将列表列表转换为列表列表?
a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
列表,我试图摆脱的元组,同时保留在列表中的数据,其结果应该是这样的
output=[['the', 'b', 'hotel', 'i'],['the', 'b', 'staff', 'i']]
太谢谢你了
我是编程新手,需要一些帮助。 我有这样如何将列表列表转换为列表列表?
a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
列表,我试图摆脱的元组,同时保留在列表中的数据,其结果应该是这样的
output=[['the', 'b', 'hotel', 'i'],['the', 'b', 'staff', 'i']]
太谢谢你了
你可以做下面的列表理解:
>>> [[y for x in i for y in x] for i in a]
[['the', 'b', 'hotel', 'i'], ['the', 'b', 'staff', 'i']]
请注意,这与元组无关,因为鸭子输入的处理方式与列表理解中的列表完全相同。您实质上是通过Making a flat list out of list of lists in Python中的多个列表项执行操作。
这可以通过sum
函数来完成:
a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
output = [sum(elem,()) for elem in a]
print(output)
如果它必须返回一个列表:
a=[[('the', 'b'), ('hotel', 'i')],[('the', 'b'), ('staff', 'i')]]
output = [sum(map(list,elem), []) for elem in a]
print(output)
@PedroLobito感谢您的输入,我更新了它。 – Neil
我想你可以使用:
output = []
for x in a:
output.append([element for tupl in x for element in tupl])
输出:
[['the', 'b', 'hotel', 'i'], ['the', 'b', 'staff', 'i']]
这里是@nfn尼尔A.
from itertools import repeat
list(map(list, map(sum, a, repeat(()))))
# -> [['the', 'b', 'hotel', 'i'], ['the', 'b', 'staff', 'i']]
你缺少你搜索的是“扁平化”的关键字的“功能性”风格的变体,如“如何扁平化列表”。 – Prune