简体   繁体   中英

Unable to filter in python using lambda

Here is the python code

languages = ["HTML", "JavaScript", "Python", "Ruby"]
print filter(lambda x: x == "Python",languages)

The output is:

[u'Python']

Where does the u come from and how to avoid it.

Required output:

['Python']

Update::

I was trying this on code academy.I guess dere was a bug in their software.

Your input contains unicode text, not str text. The u'' indicates a unicode literal.

This is probably normal, and depends entirely on where you got your languages list from . Things are otherwise working .

The CodeAcademy exercise you link to is actually broken . It shows you Python str input and but it's output uses unicode . You need to report that as a bug.

You can work around that bug by mapping everything to a str :

print filter(lambda x: x=='Python', map(str, languages))

or by mapping the output of filter to str() :

print map(str, filter(lambda x: x=='Python', languages))

which works for this case because the input only uses ASCII characters. Normally you'd encode unicode to str explicitly by specifying an encoding instead, see the Python Unicode HOWTO .

Straightforward conversion is made with:

languages = ["HTML", "JavaScript", "Python", "Ruby"]
flt = filter(lambda x: x == "Python",languages)
print [str(X) for X in flt]

Output

['Python']

Yes, the simple str() is doing conversion.

u代表unicode,您可以使用str(filter(...))将其转换为普通字符串

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