运行随机函数 [英] running a random function

查看:61
本文介绍了运行随机函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一些代码,从

函数列表中随机选择一个函数并调用它。我正在查看全局名称空间和

随机选择类型函数的项目..但我没有看到实际运行该函数的

方式。


任何指针?


-

大卫熊

- 让我买你的知识产权,我想拥有你的想法 -

解决方案

大卫熊于06/07/2007 11:56对世界说AM:


我想编写一些代码,从

函数列表中随机选择一个函数并调用它。我正在查看全局名称空间和

随机选择类型函数的项目..但我没有看到实际运行该函数的

方式。


任何指针?



除非我错过了你的意思:


>> import random
def f():print 42



....


> ;> def g():print 24



....


>> funcs = [f,g]
random.choice(funcs)()



24

Best,


Brian vdB


在< 1654405.LVbK4P6cM3@teancum> ;, David Bear写道:


我想写一些代码,可以从中随机选择一个函数一个

的功能列表并调用它。我正在查看全局名称空间和

随机选择类型函数的项目..但我没有看到实际运行该函数的

方式。



如果您有一个函数或可调用函数,则使用call operator调用它,

这是括号:


在[8]中:int

Out [8]:< type''int''>


In [9]:int()

Out [9]:0

从列表中随机选择一个元素看看​​

`random.choice()`函数。


Ciao,

Marc''BlackJack''Rintsch


你是如何制作功能列表的?这样的事情:

展开 | 选择 | Wrap | 行号


I would like to write some code that would randomly select a function from a
list of functions and call it. I was looking in the globals names space and
randomly selecting items that were of type function.. but I didn''t see a
way of actually running the function.

Any pointers?

--
David Bear
-- let me buy your intellectual property, I want to own your thoughts --

解决方案

David Bear said unto the world upon 06/07/2007 11:56 AM:

I would like to write some code that would randomly select a function from a
list of functions and call it. I was looking in the globals names space and
randomly selecting items that were of type function.. but I didn''t see a
way of actually running the function.

Any pointers?

Unless I''ve missed your meaning:

>>import random
def f(): print 42

....

>>def g(): print 24

....

>>funcs = [f,g]
random.choice(funcs)()

24
Best,

Brian vdB


In <1654405.LVbK4P6cM3@teancum>, David Bear wrote:

I would like to write some code that would randomly select a function from a
list of functions and call it. I was looking in the globals names space and
randomly selecting items that were of type function.. but I didn''t see a
way of actually running the function.

If you have a function or callable you call it with the "call operator",
which are parenthesis:

In [8]: int
Out[8]: <type ''int''>

In [9]: int()
Out[9]: 0

For a random selection of an element from a list look at the
`random.choice()` function.

Ciao,
Marc ''BlackJack'' Rintsch


How are you making the list of functions? Something like this:

Expand|Select|Wrap|Line Numbers


这篇关于运行随机函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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