[英]Remove unnecessary square brackets from output
The code below returns:下面的代码返回:
[[('direction', 'north')], [('direction', 'east')], [('direction', 'south')]]
There is a set of [ ] around each value that I'm wondering how to get rid of.每个值周围都有一组 [ ] ,我想知道如何摆脱它们。 The ideal output is:
理想的 output 是:
[('direction', 'north'), ('direction', 'east'), ('direction', 'south')]
Here is the function:这是 function:
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'))
Does anyone know why the square brackets show up in the output and how I can get rid of them?有谁知道为什么方括号出现在 output 中以及我如何摆脱它们?
Any assistance is much appreciated.非常感谢任何帮助。
Sir, you have over complicated life.先生,您的生活过于复杂。 Just use this.
就用这个。
#Note: x would be your list #注意:x 将是您的列表
new = [lst[0] for lst in x]
output output
[('direction', 'north'), ('direction', 'east'), ('direction', 'south')]
You used the wrong method to increase your outer list.您使用错误的方法来增加您的外部列表。 You appended a list of a tuple, rather than simply adding the tuple.
您附加了一个元组列表,而不是简单地添加元组。 Simply change the function to the one you need:
只需将 function 更改为您需要的:
output.extend(list(filter(lambda x:word in x, dictionary)))
Result:结果:
[('direction', 'north'), ('direction', 'east'), ('direction', 'south')]
Fix the problem where it occurs, rather than reversing the error later.修复它发生的问题,而不是稍后扭转错误。
those qotes are because your filter is transformed into a list with a tuple inside.这些 qotes 是因为您的过滤器已转换为内部包含元组的列表。 So if you only take the first element by adding [0] like this
因此,如果您只通过像这样添加 [0] 来获取第一个元素
output.append(list(filter(lambda x:word in x, dictionary))[0])
it should solve your problem.它应该可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.