这些对象中的每一个都有一个属性name
。我想检查一下这些对象中是否包含特定字符串' name
个属性。
[<bouncy.ball object at 0x7fdf8649ef10>, <bouncy.ball object at 0x7fdf863616d0>, < bouncy.ball object at 0x7fdf863616d0>]
最有效的方法是什么?
答案 0 :(得分:2)
其他答案使用您已使用的曲目(&#39;任何&#39;)为您提供答案。如果您想知道找到特定名称的球对象,可以使用:
function dump_all_meta(){
echo "<h3>All Post Meta</h3>";
// Get all the data.
$getPostCustom=get_post_custom();
foreach( $getPostCustom as $name=>$value ) {
echo "<strong>".$name."</strong>"." => ";
foreach($getPostCustom as $name=>$value) {
echo "<strong>".$name."</strong>"." => ";
foreach($value as $nameAr=>$valueAr) {
echo "<br /> ";
echo $nameAr." => ";
echo var_dump($valueAr);
}
echo "<br /><br />";
}
} // Callback funtion ended.
答案 1 :(得分:1)
如果您只需要检查一次,您可以尝试使用in运算符和生成器表达式
if "pizza" in (ball.name for ball in balls): ...
如果你要检查几次,你可以提前准备一套/ dict:
balls_names = set(ball.name for ball in balls) #build a dict if you want to use the ball after it is found...
#much later in the code...
if "pizza" in balls: ...
后一种方法将占用更多内存,但由于其O(1)查找
会更快答案 2 :(得分:0)
我认为您使用any
和生成器表达式
>>> class A:
... def __init__(self,name):
... self.name = name
...
>>> a=A('bob')
>>> b=A('mike')
>>> c=A('lelsley')
>>> l=[a,b,c]
>>> any('mike' in x.name for x in l)
True
>>> any('xyz' in x.name for x in l)
False