python在删除重复项后保留集合中的顺序

标签 python regex set

我有一个成功的代码,它将单词添加到括号中:但我需要删除其中的重复项。

我的代码:

import re
import collections

class Group:
    def __init__(self):
        self.members = set()
        self.text = []

with open('text1.txt') as f:
    groups = collections.defaultdict(Group)
    group_pattern = re.compile(r'^(\S+)\((.*)\)$')
    current_group = None
    for line in f:
        line = line.strip()
        m = group_pattern.match(line)
        if m:    # this is a group definition line
            group_name, group_members = m.groups()
            groups[group_name].members |= set(group_members.split(','))
            current_group = group_name
        else:
            if (current_group is not None) and (len(line) > 0):
                groups[current_group].text.append(line)

for group_name, group in groups.items():
    print "%s(%s)" % (group_name, ','.join(set(group.members)))
    print '\n'.join(group.text)
    print

我的文本文件:

 Car(skoda,audi,benz,bmw)
 The above mentioned cars are sedan type and gives long rides efficient
 ......

Car(audi,Rangerover,Hummer)
SUV cars are used for family time and spacious.

输出为:

Car(skoda,benz,bmw,Rangerover,Hummer,audi)
The above mentioned cars are sedan type and gives long rides efficient
......
SUV cars are used for family time and spacious.

预期输出:

Car(skoda,audi,benz,bmw,Rangerover,Hummer)
The above mentioned cars are sedan type and gives long rides efficient
......
SUV cars are used for family time and spacious.

这里奥迪是输出中的重复,我将其删除,但它插入到最后而不是第二个位置。 请帮忙!答案将不胜感激!

最佳答案

集合无序,因此您的集合不会有顺序,如果您需要维护顺序,请使用sorted按顺序排序原始列表:

members = ["skoda","audi","benz","bmw","audi","Rangerover","Hummer"]

print ','.join(sorted(set(members),key=lambda x: members.index(x)))
skoda,audi,benz,bmw,Rangerover,Hummer
  1. set(members) 删除重复项
  2. 然后我们使用 sortedlambda 创建一个排序列表
  3. 我们使用键 key=lambda x:members.index(x) 进行排序,该键根据每个元素在 members 中所在的 index 进行排序 列表。
  4. 当所有排序的 audi 根据其在原始 members 列表中的索引值放入列表中时,它会作为第二个条目返回到列表中。

因为您从一开始就使用集合,所以您会丢失顺序,并且如果没有某种维护原始顺序进行排序的结构,就无法恢复顺序。

如果您想保持顺序并在末尾使用集合来删除重复项,则可以将集合更改为列表,因此最后一步将类似于:

','.join(sorted(set(self.members),key=lambda x: self.members.index(x)))

其中 self.members 现在是一个列表,我们使用它的顺序将 set 中的项目重新排序为其原始顺序。

如果不使用容器来保持元素的原始顺序,就没有办法。

class Group:
    def __init__(self):
        self.members = []
        self.text = []

with open('text1.txt') as f:
    groups = collections.defaultdict(Group)
    group_pattern = re.compile(r'^(\S+)\((.*)\)$')
    current_group = None
    for line in f:
        line = line.strip()
        m = group_pattern.match(line)
        if m:    # this is a group definition line
            group_name, group_members = m.groups()
            groups[group_name].members += filter(lambda x: x not in groups[group_name].members , group_members.split(','))
            current_group = group_name
        else:
            if (current_group is not None) and (len(line) > 0):
                groups[current_group].text.append(line)

for group_name, group in groups.items():
    print "%s(%s)" % (group_name, ','.join(group.members))
    print '\n'.join(group.text)
    print

filter 代码相当于[x for x in group_members.split(',') if x not in groups[group_name].members]

关于python在删除重复项后保留集合中的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25327773/

相关文章:

ios - NSRegularExpression

regex - 使用 sed 添加空格

java - 方法签名中的 <E> 是什么?

java - HashSet 中有多少个唯一对象以及使用哪个方法检查唯一性等于或 hashCode

python - 为什么我的正则表达式不能与 str.contains 一起使用?

python - 符号学插值;从 y 得到 x

python - 如果不是 unicode 则解码

Python MySQLdb : Inserting duplicate entry into a table with UNIQUE fields

javascript - $error.pattern 无法正常工作

java - 为什么 Java HashMap get(key) 在使用相同的 HashMaps 迭代器读取键时比使用 Set 的迭代器读取键时工作得更快?