有序集Python 2.7 [英] Ordered Sets Python 2.7

查看:72
本文介绍了有序集Python 2.7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个尝试从中删除重复项的列表.我正在使用python 2.7.1,因此我可以简单地使用 set()函数.但是,这重新排列了我的列表.对于我的特殊情况,这是不可接受的.

I have a list that I'm attempting to remove duplicate items from. I'm using python 2.7.1 so I can simply use the set() function. However, this reorders my list. Which for my particular case is unacceptable.

下面是我写的一个函数;做到这一点.但是我想知道是否有更好/更快的方法.此外,对此的任何评论将不胜感激.

Below is a function I wrote; which does this. However I'm wondering if there's a better/faster way. Also any comments on it would be appreciated.

    def ordered_set(list_):

        newlist = []
        lastitem = None
        for item in list_:

            if item != lastitem:
                newlist.append(item)
                lastitem = item

        return newlist

以上功能假定所有项目都不为,并且项目按顺序排列(即 ['a','a','a',' b','b','c','d'] )

The above function assumes that none of the items will be None, and that the items are in order (ie, ['a', 'a', 'a', 'b', 'b', 'c', 'd'])

上面的函数返回 ['a','a','a','b','b','c','d'] 作为 ['a ','b','c','d'] .

推荐答案

使用OrderedDict:

Use an OrderedDict:

from collections import OrderedDict

l = ['a', 'a', 'a', 'b', 'b', 'c', 'd']
d = OrderedDict()

for x in l:
    d[x] = True

# prints a b c d
for x in d:
    print x,
print

这篇关于有序集Python 2.7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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