三级运作

扫码查看
本文介绍了三级运作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! x =无 结果=(x为无和&或str(x)) 打印结果,类型(结果) --------------- 输出 ------ --------- 无< type''str''> y = 5 result =(y是5和它'是5或它不是5) 打印结果 - ----------- 输出 ------------- it '是五个 "结果"是一个空字符串,而不是无的str值。x = Noneresult = (x is None and "" or str(x))print result, type(result)---------------OUTPUT---------------None <type ''str''>y = 5result = (y is 5 and "it''s five" or "it''s not five")print result-------------OUTPUT-------------it''s five....what''s wrong with the first operation I did with x? I was expecting"result" to be an empty string, not the str value of None.推荐答案 你的邪恶三级黑客已经失败了,因为空字符串 在布尔上下文中计为false。请学会喜欢新的条件表达式语法: http://docs.python.org/whatsnew/pep-308.html 空字符串的计算结果为False,因此它继续到 其他分支。以下任何一个都应该足够了: #返回一个非空字符串 x是None和None或者str(x) #颠倒逻辑并返回 #在和中的东西部分 x不是None和str(x)或" 在 $中有更多巴洛克式的编写三元运算符的方式b $ b python(虽然我理解2.5或者python 3k应该有 a这样做的真实方式)。我的理解是,一个常见的 解决方案类似于 {True:"",False:str(x)} [x is None] -tkcAn empty string evaluates to False, so it then continues to theother branch. Either of the following should suffice:# return a non-empty stringx is None and "None" or str(x)# invert the logic and return# something in the "and" portionx is not None and str(x) or ""There are more baroque ways of writing the terniary operator inpython (although I understand 2.5 or maybe python 3k should havea true way of doing this). My understanding is that one commonsolution is something like{True: "", False: str(x)}[x is None]-tkc 条件和结果1或结果2如果result1是具有True布尔值的 表达式,则该技巧才有效。空字符串有一个错误的 布尔值。 您可以通过将其粘贴到 $ b $中来强制result1具有真正的布尔值ba list: result =(x是None和["]或[str(x)])[0] 但这很难看。使用Python 2.5,其中有一个真正的条件 表达式或找到另一种方法来解决你的问题。 -CarstenThe "condition and result1 or result2" trick only works if result1 is anexpression with a True boolean value. The empty string has a falseboolean value.You could force result1 to have a true boolean value by sticking it intoa list thusly:result = (x is None and [""] or [str(x)])[0]But that''s ugly. Use Python 2.5 where there is a true conditionalexpression or find another way to solve your problem.-Carsten 这篇关于三级运作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-03 22:48
查看更多