如何在python中对元素元组进行排序,首先是基于值,然后是基于键。考虑我将用户输入作为字符串的程序。我想找出每个字符的数量,并在字符串中打印3个最常见的字符。
#input string
strr=list(raw_input())
count=dict()
#store the count of each character in dictionary
for i in range(len(strr)):
count[strr[i]]=count.get(strr[i],0)+1
#hence we can't perform sorting on dict so convert it into tuple
temp=list()
t=count.items()
for (k,v) in t:
temp.append((v,k))
temp.sort(reverse=True)
#print 3 most common element
for (v,k) in temp[:3]:
print k,v
给予i / p -aabbbccde
以上代码的输出是:
3 b
2 c
2 a
但我希望输出为:
3 b
2 a
2 c
答案 0 :(得分:5)
对元组列表进行排序,第一个值按降序排列(reverse=True
),第二个值按升序排列(reverse=False
,默认情况下)。这是一个MWE。
lists = [(2, 'c'), (2, 'a'), (3, 'b')]
result = sorted(lists, key=lambda x: (-x[0], x[1])) # -x[0] represents descending order
print(result)
# Output
[(3, 'b'), (2, 'a'), (2, 'c')]
使用collections.Counter
很简单
用字符串计算每个字母的频率。
import collections
s = 'bcabcab'
# If you don't care the order, just use `most_common`
#most_common = collections.Counter(s).most_common(3)
char_and_frequency = collections.Counter(s)
result = sorted(char_and_frequency.items(), key=lambda x:(-x[1], x[0]))[:3] # sorted by x[1] in descending order, x[0] in ascending order
print(result)
# Output
[('b', 3), ('a', 2), ('c', 2)]
答案 1 :(得分:0)
作为&#34的一般解决方案;按值降序排序,然后按键升序排序"你可以使用itertools.groupby
:
import itertools
from operator import itemgetter
def sort_by_value_then_key(count_dict):
first_level_sorted = sorted(count_dict.items(), key=itemgetter(1), reverse=True)
for _, group in itertools.groupby(first_level_sorted,itemgetter(1)):
for pair in sorted(group):
yield pair
strr=list("aabbccdef")
count=dict()
#store the count of each character in dictionary
for i in range(len(strr)):
count[strr[i]]=count.get(strr[i],0)+1
temp = list(sort_by_value_then_key(count))
for (letter, freq) in temp[:3]:
print letter, freq
输出:
a 2
b 2
c 2
因为你正在使用整数@ sparkandshine的负数排序解决方案可能更容易使用,但这更加通用。