我能操纵sorted()组织事物的方式吗?

2024-06-09 20:48:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理大量的数据(元组列表),我想组织这些数据。更具体地说:

# my characters for the items in the strings are 1-9,a-e
# the results of my previous program produce a list of tuples
# e.g. ('string', int), where int is the count of occurrence of that string in my data
# my program currently lists them by count order, starting highest to lowest

>>> print results #results from the previous part of my code
[('7b7', 23522), ('dcd',23501)....('ccc',1)]

>>> for three_grams in results:
    print (sorted(three_grams))

[23522, '7b7']
[23501, 'dcd']
....
[1, 'ccc']

我不知道为什么它会切换int和string。。。 但我想用相反的方式来分类。理想情况下

[('111',803), ('112', 2843), ('113', 10)....('fff', 12)]

有没有办法操纵sorted()函数的排序方式?我可以改为在元组的字符串位中按1-9a-e排序吗?你知道吗

(另外,我以前生成这些结果的程序不打印计数为零的结果,我希望得到一些帮助。不确定我是应该在这里发布,还是在那里用我的全部代码再讨论一个问题?什么是礼节?我还是新手)


Tags: ofthe数据inforstringmycount
2条回答

您正在对单个结果进行排序。你知道吗

您需要对所有结果进行排序。你知道吗

sorted可以采用key参数。从the documentation

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

我们将使用result[0]作为比较键,即'7b7''dcd''ccc'

>>> results = [('7b7', 23522), ('dcd',23501), ('ccc',1)]

>>> sorted(results, key=lambda result: result[0])
[('7b7', 23522), ('ccc', 1), ('dcd', 23501)]

如果您不喜欢lambda,可以使用^{}

>>> from operators import itemgetter
>>> sorted(results, key=itemgetter(0))
[('7b7', 23522), ('ccc', 1), ('dcd', 23501)]

你可以像这样定义一个字典,它有点像十六进制系统(除了基数14):

valuesdict = {'a': 10, 'c': 12, 'b': 11, 'e': 14, 'd': 13, '1': 1, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}

添加一个函数,用于计算以14为基数的系统中字符串的十进制值(以10为基数)。你知道吗

base = 14
def base10value(text):  

    count = len(text)-1
    finalValue = 0

    for character in text:
        number = valuesdict[character]
        finalValue += number*math.pow(base,count)
        count -= 1

    return finalValue

然后在元组列表中使用lambda函数

print sorted(tuple,key = lambda x: base10value(x[0]))

相关问题 更多 >