从列表中查找具有等于某个值的属性,然后获取下一个对象

时间:2015-03-11 21:19:10

标签: python python-2.7 itertools

我能够找到一个对象,其属性等于某个值。但我想从列表中获取对象(如果找到的对象是列表中的最后一个对象,那么之后的下一个对象应该是第一个对象)。类似的东西:

from pprint import pprint

class User(object):
    def __init__(self, name):
        self.name = name

users = []
users.append(User("Peter"))
users.append(User("James"))
users.append(User("John"))

#   find object that has attribute name equal to James
pprint(vars([user for user in users if user.name == "James"][0]))

pprint行的输出打印:

{'name': 'James'}

这是正确的。

我想问你如何在"James"之后获取下一个对象,以及在"John"应该返回"John"之后我是否会搜索"Peter"下一个对象。建议?

我也试过了itertools,但是如果找到的元素是最后一个,我就无法得到下一个元素:

from itertools import enumerate
_i = next(i for i, user in enumerate(users) if (user.name == "John"))
print users[_i + 1] #this is not working 

我可以在操作[_i+1]之前添加if条件来更改计数器,但我想知道是否有更平滑的解决方案吗?

4 个答案:

答案 0 :(得分:1)

要处理最后一个元素,您可以使用modulo:index % len(users)

这是一种方式:

def find_after_name(users, name):
    for i, user in enumerate(users):
        if user.name == name:
            return users[(i+1) % len(users)]

另一个选项是zip带有列表移位副本的列表。 deque.rotate()对此类转变非常有用:

from collections import deque
def find_after_name(users, name):
    users2 = deque(users)
    users2.rotate(-1)
    for user1, user2 in zip(users1, users2):
        if user1.name == name:
            return user2

答案 1 :(得分:1)

既然您已选择使用OOP,为什么不实现从内置列表类继承的UserList类?

class User(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return repr(self)

    def __repr__(self):
        return "User('{0}')".format(self.name)


class UserList(list):
    def find(self, name):
        for k, user in enumerate(self):
            if user.name == name:
                return k, user

    def next_to(self, name):
        """get user next to the one of name (e.g. 'James')"""
        index, user = self.find(name)
        next_to_index = self.get_next_to_index(index)
        return self[next_to_index]

    def get_next_to_index(self, index):
        next_to_index = index + 1
        if next_to_index == len(self):
            # meaning index is already the last element, need to reset index
            next_to_index = 0
        return next_to_index


users = UserList()
users.append(User("Peter"))
users.append(User("James"))
users.append(User("John"))

print users.find('James')
print users.next_to('James')
print users.next_to('John')

输出:

(1, User('James'))
User('John')
User('Peter')

答案 2 :(得分:1)

对于踢,我想看看是否有一个itertools解决方案:

from itertools import dropwhile
def find_after_name(users, name):
    for i, _ in dropwhile(lambda eu: eu[1].name != name, enumerate(users)):
        return users[(i+1) % len(users)]

注意:确实应该有一个list.index(value,key = None)方法,其中key就像list.sort()的key参数。然后你可以做这样的事情:

index = users.index("John", key=lambda u: u.name)

答案 3 :(得分:1)

解决方案扩展列表类:

class extended_list(list):
    def index(self, value, key=None):
        if key is None:
            return super().index(self, value)
        try:
            return next(i for i,o in enumerate(self) if value == key(o))
        except StopIteration:
            raise ValueError("{} is not in list".format(repr(value)))


def find_after_name(users, name):
    i = extended_list(users).index(name, key=lambda u: u.name)
    return users[(i+1) % len(users)]