Python 从输出中删除不必要的方括号

Python 从输出中删除不必要的方括号,python,python-3.x,Python,Python 3.x,下面的代码返回: [[('direction', 'north')], [('direction', 'east')], [('direction', 'south')]] 每个值周围都有一组[],我想知道如何去除这些值。理想的输出是: [('direction', 'north'), ('direction', 'east'), ('direction', 'south')] 以下是函数: def scan(input): words = input.split() dic

下面的代码返回:

[[('direction', 'north')], [('direction', 'east')], [('direction', 'south')]]
每个值周围都有一组[],我想知道如何去除这些值。理想的输出是:

[('direction', 'north'), ('direction', 'east'), ('direction', 'south')]
以下是函数:

def scan(input):
    words = input.split()
    dictionary = [('direction', 'north'),('direction', 'south'),('direction', 'east')]
    output = []
    for word in words:
        output.append(list(filter(lambda x:word in x, dictionary)))
    return output

print(scan('north east south'))
有人知道为什么方括号会出现在输出中,以及我如何消除它们吗


非常感谢您的帮助。

先生,您的生活太复杂了。就用这个

#注:x将是您的列表

new = [lst[0] for lst in x]
输出

[('direction', 'north'), ('direction', 'east'), ('direction', 'south')]

这些Qote是因为过滤器被转换成一个包含元组的列表。因此,如果您仅通过像这样添加[0]来获取第一个元素

output.append(列表(过滤器(lambda x:x中的单词,字典))[0])

这应该可以解决您的问题。

您使用了错误的方法来增加外部列表。您附加了一个元组列表,而不是简单地添加元组。只需将功能更改为您需要的功能:

    output.extend(list(filter(lambda x:word in x, dictionary)))
结果:

[('direction', 'north'), ('direction', 'east'), ('direction', 'south')]
在出现问题的地方进行修复,而不是在以后逆转错误