英文:
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 'ledId' 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] > 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]) > 1]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论