用于在python中排序多维数组的适当数据结构? [英] appropriate data structure for sorting a multi dimensional array in python?

查看:145
本文介绍了用于在python中排序多维数组的适当数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我想组织成一个多维数组,然后排序的各种字符串(单词),我有三个数值(权重,计数,贡献)。为了做到这一点,我在一个字典中列出了列表,数值在列表中,字符串是关键字:

  print_dictionary [word] = [weight,count,contribution] 

我如何排序,先按升序排列然后按降序排列,通过贡献(列表中的第三个值),并显示排序列表的前10个项目。如何做到这一点?



例如,对于以下print_dictionary:

  print_dictionary [sam] = [2,7,1] 
print_dictionary [sun] = [4,1,3]
print_dictionary [dog] = [1,3,2]

我希望他们能够按升序排序捐款:

  Word:Weight:Count:Contribution:
sam 2 7 1
dog 1 3 2
sun 4 1 3

我看不到如何使用itemegetter:

  sorted(print_dictionary,key = itemgetter(2))


解决方案

您可以传递一个匿名函数作为排序的键。这使用多维dict的第三个成员作为关键:

 >>> d = {'a':[1,4,7],'b':[2,3,9],'c':[3,2,8]} 
>>> (d,key = lambda x:d [x] [2]):
...打印键,d [键]
a [1,4,7]
c [3,2,8]
b [2,3,9]

,使用 reverse = True 。要限制结果,请添加 [:N]

  d,key = lambda x:d [x] [2],reverse = True)[:2] 

#b [2,3,9]
#c [3,2 ,8]

更多关于排序并在Python中进行排序


I have three numeric values (weight, count, contribution) for various strings (words) that i would like to organise into one multidimensional array, and then sort. To do this, I made lists within a dictionary, where the numeric values are in the list and the string is the key:

print_dictionary[word] = [weight,count,contribution]

How can I sort, first in ascending order and then in descending order, by 'contribution' (the third value in the list), and show the first 10 items of the sorted list. How can I do this?

For example, for the following print_dictionary:

print_dictionary[sam] = [2,7,1]
print_dictionary[sun] = [4,1,3]
print_dictionary[dog] = [1,3,2]

I want to them be able to sort contribution in ascending order:

Word:   Weight:   Count:    Contribution:
sam     2         7         1
dog     1         3         2
sun     4         1         3

I don't see how itemegetter can be used for this:

sorted(print_dictionary, key=itemgetter(2))

解决方案

You can pass an anonymous function as the key to sorted. This uses the third member of the multi-dimensional dict as the key:

>>> d = {'a': [1, 4, 7], 'b': [2, 3, 9], 'c': [3, 2, 8]}
>>> for key in sorted(d, key=lambda x: d[x][2]):
...    print key, d[key]
a [1, 4, 7]
c [3, 2, 8]
b [2, 3, 9]

For descending order, use reverse=True. To limit the results, add [:N]:

sorted(d, key=lambda x: d[x][2], reverse=True)[:2]

# b [2, 3, 9]
# c [3, 2, 8]

More about sorted and sorting in Python.

这篇关于用于在python中排序多维数组的适当数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆