简体   繁体   中英

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:

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

Here is the 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?

Any assistance is much appreciated.

Sir, you have over complicated life. Just use this.

#Note: x would be your list

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

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:

    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. So if you only take the first element by adding [0] like this

output.append(list(filter(lambda x:word in x, dictionary))[0])

it should solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM