从对象列表中选择其中一个数值出现多次的对象。

huangapple go评论76阅读模式
英文:

Select from a list of objects where a value occurs more than once

问题

我在Python中有一个以下自定义对象的列表我想创建一个新的对象列表其中'ledId'出现超过一次类似于基于ID的重复项列表)。

#### 对象

```python
class CustomObject:
    def __init__(self, id, ledId):
        self.id = id
        self.ledId = ledId

通常我使用C#,所以我想做类似于以下的操作:

subList = [obj for obj in myList if myList.count(lambda l: l.ledId == obj.ledId) > 1]

在Python中是否有一种简单的方法来实现这个?


<details>
<summary>英文:</summary>

I have a list of the below custom object in python. I want to create a new list of objects where the &#39;ledId&#39; more than once (like a list of duplicates based on an id)



#### The object

class CustomObject:
def init(self, id, ledId):
self.id = id
self.ledId = ledId


I usually use C# so I am wanting to do something like

var subList = myList.Where(obj => myList.Count(l => l.ledId == obj.ledId) > 1)
.ToList();


Is there an easy way to do this in python?

</details>


# 答案1
**得分**: 2

其他解决方案会起作用,但值得注意的是,这里提供的算法的时间复杂度为 O(n^2),因为你在每次迭代中都运行 `count`。你可以通过只计数一次并将结果存储在一个 `dict` 中来将其优化为 O(n):

```python
from collections import defaultdict

counts = defaultdict(int)

for custom_object in sub_list:
    counts[custom_objects.ledId] += 1

result = [x for x in sub_list if counts[x.ledId] > 1]

这也是使用 defaultdict 的绝佳机会,但你会失去 C# 中非常功能性的方法,以使其更具“Pythonic”特色。

英文:

The other solutions will work, but for the record, the algorithm as presented here is in O(n^2), since you run the count for each iteration. You can make it O(n) by counting once, and storing the result in a dict:

from collections import defaultdict

counts = defaultdict(int)

for custom_object in sub_list:
    counts[custom_objects.ledId] += 1

result = [x for x in sub_list if counts[x.ledId] &gt; 1]

It is also a great opportunity to use defaultdict, but you do lose the very functional approach from C#, to make it more "Pythonic".

答案2

得分: 0

重写你的代码从C#到Python大致如下:

[a for a in some_list if len([b for b in some_list if b.ledId == a.ledId]) > 1]
英文:

Rewriting you code in C# to Python would be something like this:

[a for a in some_list if len([b for b in some_list if b.ledId == a.ledId]) &gt; 1]

huangapple
  • 本文由 发表于 2023年2月27日 16:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577990.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定