[英]Unable to filter in python using lambda
Here is the python code 这是python代码
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. u
来自哪里,如何避免它。
Required output: 要求的输出:
['Python']
Update:: 更新::
I was trying this on code academy.I guess dere was a bug in their software. 我在代码学院尝试过这个。我猜dere是他们软件中的错误。
Your input contains unicode
text, not str
text. 您的输入包含unicode
文本,而不是str
文本。 The u''
indicates a unicode
literal. u''
表示unicode
文字。
This is probably normal, and depends entirely on where you got your languages
list from . 这可能是正常现象,并且完全取决于您从中获取languages
列表的位置 。 Things are otherwise working . 否则事情就开始运转了 。
The CodeAcademy exercise you link to is actually broken . 您链接到的CodeAcademy练习实际上已中断 。 It shows you Python str
input and but it's output uses unicode
. 它向您显示Python str
输入,但其输出使用unicode
。 You need to report that as a bug. 您需要将其报告为错误。
You can work around that bug by mapping everything to a str
: 您可以通过将所有内容映射到str
来解决该错误:
print filter(lambda x: x=='Python', map(str, languages))
or by mapping the output of filter
to str()
: 或通过将filter
的输出映射到str()
:
print map(str, filter(lambda x: x=='Python', languages))
which works for this case because the input only uses ASCII characters. 在这种情况下有效,因为输入仅使用ASCII字符。 Normally you'd encode unicode
to str
explicitly by specifying an encoding instead, see the Python Unicode HOWTO . 通常,您可以通过指定编码来将unicode
显式编码为str
,请参见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. 是的,简单的str()
正在进行转换。
u
代表unicode,您可以使用str(filter(...))
将其转换为普通字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.