188*_*881 5 python arrays sorting
我只想按降序查找前 3 个不同的项目。如果有决胜局,请按字母顺序排序。如果有 3 个或更少的项目,返回不同的项目列表就足够了。
所以如果我有输入: ["a","a","b","b","c","c","c","d","d","d","d"]
输出将是 ["d","c","a"]
因为 d 有 4 个计数,c 有 3 个计数,a并且b具有相同的频率,但a按字母顺序排在第一位。
在 MySQL 中,我通常会使用这个:
SELECT id, COUNT(*) as frequency FROM mylist GROUP BY id ORDER BY frequency, id
Run Code Online (Sandbox Code Playgroud)
我怎样才能在 Python 中做到这一点?
我使用基于SAI SANTOH CHIRAG 解决方案的代码:
def main(output):
arr = sorted(output,key=lambda i:[output.count(i),-ord(i)],reverse=True)
out = []
for i in arr:
if i not in out: out.append(i)
print(out[:3])
Run Code Online (Sandbox Code Playgroud)
但为什么结果是这样的:
Input (stdin) = a a a b b c d d d d
output = ['d']
['d']
['d']
['d']
['d', 'a']
['d', 'a']
['d', 'a']
['d', 'a', 'b']
['d', 'a', 'b']
['d', 'a', 'b']
Run Code Online (Sandbox Code Playgroud)
而不是我想要的,这将是:
['d','a','b']
Run Code Online (Sandbox Code Playgroud)
您可以使用排序和键来实现这一点。尝试这样:
arr = sorted(x,key=lambda i:[x.count(i),-ord(i)],reverse=True)
Run Code Online (Sandbox Code Playgroud)
这样,您就可以按计数增加的顺序获得所有元素,然后按字母顺序排列。然后执行以下操作以仅获取所有元素一次:
out = []
for i in arr:
if i not in out:
out.append(i)
print(out[:3])
Run Code Online (Sandbox Code Playgroud)