簡體   English   中英

Python列表按每個唯一值獲取前n個元素

[英]Python List get first n elements by each unique value

我有一個清單;

    [('10', '100'),
     ('11', '100'),
     ('18', '108'),
     ('22', '100'),
     ('12', '102'),
     ('15', '104'),
     ('21', '100'),
     ('25', '108'),
     ('20', '102'),
     ('24', '104'),
     ('105', '108'),
     ('35', '100'),
     ('14', '104'),
     ('96', '100'),
     ('100', '104'),
     ('26', '100'),
     ('19', '100'),
     ('110', '108'),
     ('36', '102'),
     ('30', '104')]

所有項目的第二個值都是唯一的“ 100”,“ 102”,“ 104”和“ 108”。

我想取'100','102','104','108'組的前3個值。

輸出應如下所示:

    [('10', '100'),
     ('11', '100'),
     ('22', '100'),
     ('18', '108'),
     ('25', '108'),
     ('105', '108'),
     ('12', '102'),
     ('20', '102'),
     ('36', '102'),
     ('15', '104'),
     ('24', '104'),
     ('14', '104')]

我不想將列表更改為數據框並使數據框工作。

您可以使用itertools.groupby

from itertools import groupby
new_d = [(a, list(b)) for a, b in groupby(sorted(d, key=lambda x:int(x[-1])), key=lambda x:int(x[-1]))]
result = [b for _, c in new_d for b in c[:3]]

輸出:

[('10', '100'), 
('11', '100'), 
('22', '100'), 
('12', '102'), 
('20', '102'), 
('36', '102'), 
('15', '104'), 
('24', '104'), 
('14', '104'), 
('18', '108'), 
('25', '108'), 
('105', '108')]

您可以遍歷元組列表,並使用字典來跟蹤元組中第二個元素出現了多少次。 如果它的第二個值出現少於3次,則只需將一個元組添加到結果列表中:

d = {}
n = 3
out = []
for i,j in l:
    if d.setdefault(j,0) < n:
        d[j]+= 1
        out.append((i,j))

print(out)

[('10', '100'),
 ('11', '100'),
 ('18', '108'),
 ('22', '100'),
 ('12', '102'),
 ('15', '104'),
 ('25', '108'),
 ('20', '102'),
 ('24', '104'),
 ('105', '108'),
 ('14', '104'),
 ('36', '102')]

一種替代方法是對字典中鍵的外觀進行簡單計數,然后對其進行排序(例如,假設輸入數據與問題相同):

from collections import defaultdict
from itertools import count
from operator import itemgetter

counts = defaultdict(lambda: count(0))
result = [(value, key) for value, key in data if next(counts[key]) < 3]

print(sorted(result, key=itemgetter(1)))

輸出量

[('10', '100'), ('11', '100'), ('22', '100'), ('12', '102'), ('20', '102'), ('36', '102'), ('15', '104'), ('24', '104'), ('14', '104'), ('18', '108'), ('25', '108'), ('105', '108')]

有關更多詳細信息,請參見countdefaultdictitemgetter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM