在 Python 2.2 中对列表进行重复数据删除和排序
在Python 2.2(不要问)中,对列表进行排序和删除重复项的最简洁方法是什么?
显然,我可以编写一个函数,该函数将 sort()
然后进行迭代,但我想知道是否有一个惯用的单行代码。
编辑:列表很短,因此效率不是问题。此外,元素是不可变的。
In Python 2.2 (don't ask), what's the neatest way to sort a list and remove duplicates?
I can obviously write a function that would sort()
then iterate, but am wondering if there's an idiomatic one-liner.
edit: The list is short, so efficiency is not a concern. Also, the elements are immutable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于旧的 python 版本,由于您使用的是字符串,所以我无法想到单行代码,但使用字典的模式可能是这样的:
改编自古老的 ActiveState 代码片段线程,Alex Martelli 本人在其中写了几条评论: http://code.activestate.com/recipes/52560/
一种更短的方法列表推导式:
除了 Steven 简洁的(但有点不吸引人的)一行,我认为这将朝着使用 Python 2.2 最少的行数和最惯用的方式进行:
感谢 Steven Rumbalski 的评论,第二个版本可以进一步压缩为python 的
zip
函数:如果
list.sort()
没有副作用,我们就会有一个衬垫。 ;)For old python versions, and since you're using strings, there's no one-liner I can think of, but a pattern would probably be this, using dictionaries:
Adapted from an ancient ActiveState code snippet thread that Alex Martelli himself wrote several comments on: http://code.activestate.com/recipes/52560/
A shorter way with list comprehensions:
Aside from Steven's neat (yet slightly unattractive) one liner, I think this heads toward the fewest lines and most idiomatic way of doing it with Python 2.2:
Thanks to Steven Rumbalski in the comments, the 2nd version can be condensed further with python's
zip
function:If
list.sort()
didn't operate by side effect, we'd have a one liner. ;)惯用语和一句台词?不,
这是一句不惯用的、丑陋的俏皮话。
如果一个简单的两行代码是可以接受的:
或者制作两个小辅助函数(适用于任何序列):
给出
最后,一个半Python式的单行代码:
Idiomatic and a one-liner? No.
Here's a non-idiomatic butt-ugly one-liner.
If a simple two-liner is acceptable:
Or make two small helper functions (works for any sequence):
gives
And finally, a semipythonic one liner:
根据记录,Python 2.2 确实有集合,但是在“集合”模块下,所以这会给你带来很大的帮助:
For the record, Python 2.2 does have sets, but under the "sets" module, so this will get you a long way:
也许最好的答案是使用二叉树:
绝对不惯用,但应该很快。它基本上创建一个基于树的集合并对其进行迭代。我没有 Python 2.2 所以希望它能工作:p
Probably the best answer is to use a binary tree:
Definitely not idiomatic, but should be fast. It basically creates a tree-based set and iterates over it. I don't have Python 2.2 so hopefully it works :p