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

2024-10-04 09:17:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类Move,它有三个属性:newPos、oldPos和notation。符号是一个字符串。我生成了一个移动列表,我想检查它们的符号是否相同。做这件事最有可能的方法是什么?我能想到的最干净的解决办法是:

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

它工作得很好,但它似乎效率低下,不太像Python。有没有一种更干净的方法来获取所有与列表中的另一个移动具有相同符号的移动?你知道吗


Tags: 方法字符串in列表formoveif属性
3条回答

像这样的?一个小的双列表理解动作

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]]

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

duplicateNotationMoves = list(filter(lambda move : len(m for m in moves if m.notation == move.notation) > 1, moves))
#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]

相关问题 更多 >