返回列表中与另一个对象具有相同属性的所有对象?

时间:2014-10-21 15:57:22

标签: python

我有一个Move类,它有三个属性:newPos,oldPos和notation。符号是一个字符串。我生成一个移动列表,我想检查其中任何一个的符号是否相同。什么是最pythonic的方式来做到这一点?我能想到的最干净的解决方案是:

duplicateNotationMoves = []
for move in moves :
    if len([m for m in moves if m.notation == move.notation]) :
        duplicateNotationMoves.append(move)

它工作正常,但似乎效率低下而且不是非常pythonic。是否有更简洁的方法来获得与列表中另一个移动具有相同符号的所有移动?

3 个答案:

答案 0 :(得分:0)

这样的事情?一个小双重列表理解行动

import random

class move: # i just made a simplified version that randomly makes notations
    def __init__(self):
        self.notation = str(random.randrange(1,10))
    def __repr__(self): #so it has something to print, instead of <object@blabla>
        return self.notation


moves = [move() for x in range(20)] #spawns 20 of them in a list

dup = [[y for y in moves if x.notation == y.notation] for x in moves] #double list comprehension


>>> dup
[[4, 4, 4], [7, 7, 7, 7], [1], [2, 2], [8, 8, 8, 8, 8], [8, 8, 8, 8, 8], [4, 4,4], [7, 7, 7, 7], [3, 3], [7, 7, 7, 7], [4, 4, 4], [6, 6], [2, 2], [8, 8, 8, 8,8], [8, 8, 8, 8, 8], [9], [6, 6], [8, 8, 8, 8, 8], [3, 3], [7, 7, 7, 7]]

答案 1 :(得分:0)

我找到了一种更简洁的方法,但它牺牲了一些易读性:

duplicateNotationMoves = list(filter(lambda move : len(m for m in moves if m.notation == move.notation) > 1, moves))

答案 2 :(得分:0)

#UNTESTED

# First, collect the data in a useful form:
notations = collections.Counter(move.notation for move in moves)

# If you want the notations that are duplicated:
duplicate_notations = [
    notation
    for notation, count in notations.items()
    if count > 1]

# Or, if you want the moves that have duplicate notations:
duplicate_moves = [
    move
    for move in moves
    if notations[move.notation] > 1]