Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否返回列表中与其他对象具有相同属性的所有对象?_Python - Fatal编程技术网

Python 是否返回列表中与其他对象具有相同属性的所有对象?

Python 是否返回列表中与其他对象具有相同属性的所有对象?,python,Python,我有一个类Move,它有三个属性:newPos、oldPos和notation。符号是一个字符串。我生成了一个移动列表,我想检查它们的符号是否相同。做这件事的最有可能的方式是什么?我能想到的最干净的解决方案是: duplicateNotationMoves = [] for move in moves : if len([m for m in moves if m.notation == move.notation]) : duplicateNotationMoves.a

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

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

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

类似的内容?一个小的双重列表理解动作

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

我的投票结果是:我要列出一个移动标记。2.从那张单子上选一张。3查找计数大于1的所有符号。因此,您要创建一个列表,其中包含具有匹配符号的列表?,听起来几乎像是要在列表理解中进行列表理解。
#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]