我有一个User类和该User类的实例列表。检查列表中是否存在用户的属性之一等于某个值,然后使用相同的逻辑将其删除的最快方法是什么?
我在以下代码中已注释了三种方法(A,B和C):
#The class
class User(object):
def __init__(self, n):
self.n = n
#The list of Users
theList = [User(10),User(15),User(20)]
#Method A
for user in theList:
if user.n == 10:
theList.remove(next(x for x in theList if x.n == 10))
print "Removed user"
break
else:
print "User does not exist"
#Method B
for index, user in enumerate(theList):
if user.n == 15:
del theList[index]
print "Removed user"
break
else:
print "User does not exist"
#Method C
try:
theList.remove(next(x for x in theList if x.n == 20))
print "Removed user"
except:
print "User does not exist"
这三个都给了我预期的结果,但是我应该使用哪个呢?有更好的方法吗?
我正在寻找C#的LINQ语句的等效项,如下所示:
theList.Any(x=>x.n == 10) //Returns true if exists
!theList.All(x=>x.n != 15) //Returns true if none of the objects are equal to 15
theList.Remove(x=>x.n == 20) //Removes from list where n is equal to 20
theList.Find(x=>x.n == 25) //Returns instance of object where n is equal to 25
非常感谢您的帮助