简体   繁体   中英

Returning all objects in list which have the same attribute as another object?

I have a class Move, which has three attributes: newPos, oldPos, and notation. Notation is a string. I generate a list of moves, and I want to check if the notation is the same for any of them. What would be the most pythonic way to do this? The cleanest solution I could think of was this :

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

It works fine, but it seems inefficient and not very pythonic. Is there a cleaner way to get all the moves that have the same notation as another move in the list?

something like this? a little double list comprehension action

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM