Python等同于C技巧 [英] Python equivalent to a C trick

查看:103
本文介绍了Python等同于C技巧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C中是否存在相当于此技巧的python?


Logic_Test? True_Result:False_Result


示例:

printf(你有%i%s,num_eggs,num_eggs> 1?" eggs":" ; egg");

解决方案

2004年8月9日23:55:08 -0700,Dan< da ******** **@gmail.com>写道:

在C中是否有一个python相当于这个技巧?

Logic_Test? True_Result:False_Result

示例:
printf(你有%i%s,num_eggs,num_eggs> 1?" eggs":egg);



打印你有%i%s %(num_eggs,(egg,鸡蛋)[num_eggs> 1])


但我不知道int(False)== 0和int (真)== 1实际上是

保证。而且我不会使用它,因为它很丑(恕我直言)。


你没有得到仅评估一个好的?:


-

Sam Holden


Dan写道:

在C中是否有一个python相当于这个技巧?

Logic_Test? True_Result:False_Result


Logic_Test和True_Result或False_Result

将是Python对应物。

例如:
printf( 你有%i%s,num_eggs,num_eggs> 1?" eggs":egg);




所以exmaple被转换为:

print"你有%d%s"%(num_eggs,(num_eggs> 1)和eggs或egg)


但是请注意,如果True_Result被评估为False(例如True_Result

是一个空字符串),这不起作用。


如果你不知道Python中哪个对象被认为是假的,请查看

以下文档。


* 2.3.1真值测试
< a rel =nofollowhref =http://docs.python.org/lib/truth.html\"target =_ blank> http://docs.python.org/lib/truth.html


-

George


Dan写道:

是在C中有一个python相当于这个技巧?

Logic_Test? True_Result:False_Result




你的问题的答案很长是
http://www.python.org/peps/pep-0308.html


(in除了hack之外,Sam发布了:-)


Roger


Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result

Example:
printf( "you have %i %s", num_eggs, num_eggs > 1 ? "eggs" : "egg" );

解决方案

On 9 Aug 2004 23:55:08 -0700, Dan <da**********@gmail.com> wrote:

Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result

Example:
printf( "you have %i %s", num_eggs, num_eggs > 1 ? "eggs" : "egg" );



print "you have %i %s" % ( num_eggs, ("egg","eggs")[num_eggs>1] )

But I don''t know if int(False)==0 and int(True)==1 are actually
guaranteed. And I wouldn''t use it since it''s ugly (IMHO).

You don''t get the "only evaluate one" goodness of ?:

--
Sam Holden


Dan wrote:

Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result
Logic_Test and True_Result or False_Result
would be a Python counterpart.
Example:
printf( "you have %i %s", num_eggs, num_eggs > 1 ? "eggs" : "egg" );



So the exmaple is converted to:
print "you have %d %s"%(num_eggs, (num_eggs > 1) and "eggs" or "egg")

But be warned that if True_Result is evaluated as False(e.g. True_Result
is an empty string), this doesn''t work.

If you don''t know what object is considered False in Python, check the
following document.

* 2.3.1 Truth Value Testing
http://docs.python.org/lib/truth.html

--
George


Dan wrote:

Is there a python equivalent of this trick in C?

Logic_Test ? True_Result : False_Result



The long answer to your question is at
http://www.python.org/peps/pep-0308.html

(in addition to the "hack" Sam posted :-)

Roger


这篇关于Python等同于C技巧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆