使用对象列表对嵌套列表进行排序
您好,我试图弄清楚如何按多个变量对嵌套列表进行排序,而有些变量不会按 1,2,3 排序,而是按预定列表排序。
例如:
List=[[XD,1],[XD,3],[XD,2],[X5,2],[X5,3],[XT,2]]
这将导致:
[[XD,1],[XD,2],[XD,3],[XT,2],[X5,2],[X5,3]]
第一个元素将按 sortbylist 排序,第二个元素仅按数字顺序排序。
SortByList={'XD': 'A', 'XT':'B', 'XQ': 'C','X5': 'D'}
我目前一直在尝试使用该代码:
List.sort(key=SortByList.__getitem__ x: x[0])
List=sorted(List,key=itemgetter(1))
但这似乎不起作用。有什么提示吗?
最简单的方法之一是:
Result=sorted(List, key=lambda x:(SortByList[x[0]],x[1]))
Hello I am trying to figure out how to sort a nested list by multiple variables while some will not be sorted by 1,2,3 and instead by a predetermined list.
For Example:
List=[[XD,1],[XD,3],[XD,2],[X5,2],[X5,3],[XT,2]]
This would result in:
[[XD,1],[XD,2],[XD,3],[XT,2],[X5,2],[X5,3]]
The first element would be sorted by the sortbylist and the second element simply in numerical order.
SortByList={'XD': 'A', 'XT':'B', 'XQ': 'C','X5': 'D'}
I have currently been trying to use the code:
List.sort(key=SortByList.__getitem__ x: x[0])
List=sorted(List,key=itemgetter(1))
This however does not seem to work. Any hints?
One of the easiest ways to do this is:
Result=sorted(List, key=lambda x:(SortByList[x[0]],x[1]))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
这使用了您问题中所解释的二元素复合键。
How about:
This uses a two-element compound key as explained in your question.
这里的问题是,您尝试使用对象的名称对对象进行排序以获得排序顺序,但您的对象没有任何对其名称的引用。除非在
locals()
或中搜索,否则无法从您的对象
。XD
得知它被称为'XD'
>全局()这里最好的选择是将变量存储在字典中,而不是直接存储在作用域/命名空间中。因此,将您的代码从以下位置更改为
:
List
的内容将完全相同,但现在您有一种方法可以关联名称'XD'
,>'X5' 和
'XT'
带有一个对象,因此在定义SortList
时,您可以按 这样你就可以创建你的SortByList
即使某些变量未定义,例如本例中的XQ
。SortByList
中的该条目只是None
,当其他元素排序时,这不会导致任何问题。The problem here is that you are trying to sort objects using their name to get the sort order, but your objects don't have any reference to what their name is. There is no way to tell from your object
XD
that it is called'XD'
except by searching for it inlocals()
orglobals()
.Your best option here is to store your variables in a dictionary rather than in directly in the scope/namespace. So change your code from this:
To this:
The contents of
List
will be exactly the same, but now you have a way to associate the names'XD'
,'X5'
, and'XT'
with an object, so when definingSortList
you can create a list of the actual objects by their name:By doing it this way you can create your
SortByList
even when some variables are undefined, likeXQ
would be in this example. That entry inSortByList
would just beNone
, which wouldn't cause any problems when the other elements are sorted.