【问题标题】:Python - Removing duplicates elements while remain the indexPython - 在保留索引的同时删除重复元素
【发布时间】:2020-10-02 03:10:36
【问题描述】:

我有两个列表,例如:

x = ['A','A','A','B','B','C','C','C','D']
list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109']

我想删除列表中的重复元素,可以通过Removing elements that have consecutive duplicates中的答案来实现

但是,我期望的输出是这样的

['A','B','C','D']
['0101','0104','0106','0109']

那是

对于 x,我想删除重复的元素。

对于 list_date,我想保留基于 x 中剩余元素的日期。

你有什么方法可以实现吗?


2020-06-14 更新:

感谢您的回答!

我的数据也有案例

y = ['A','A','A','B','B','C','C','C','D','A','A','C','C','B','B','B']
list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109','0110','0111','0112','0113','0114','0115','0116']

输出应该是

['A','B','C','D','A','C','B']
['0101','0104','0106','0109','0110','0112','0114']

我应该如何处理这样的列表?

【问题讨论】:

  • 所以您想从list_date 中删除从x 中删除的职位?如果您的数据是链接的,您是否有理由使用两个列表而不是一个字典?

标签: python list duplicates


【解决方案1】:

您可以使用 zip() 将数据与日期耦合,使用循环和集合来删除重复项,然后再次使用 zip() 从中获取单个列表:

x = ['A','A','A','B','B','C','C','C','D']
list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109']

r = []
k = zip(x,list_date)
s = set()

# go over the zipped values and remove dupes
for el in k:
    if el[0] in s:
        continue
    # not a dupe, add to result and set
    r.append(el)
    s.add(el[0])

data, dates = map(list, zip(*r))

print(data)
print(dates)

输出:

['A', 'B', 'C', 'D']
['0101', '0104', '0106', '0109']

How to iterate through two lists in parallel?

【讨论】:

    【解决方案2】:

    在下面试试这个:

    x = ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'D']
        list_date = ['0101', '0102', '0103', '0104', '0105', '0106', '0107', '0108', '0109']
        op = dict()
        y = []
        for i in range(len(x)):
            if x[i] not in y:
                y.append(x[i])
                op[x[i]] = list_date[i]
    
        z = list(op.values())
        print(y)
        print(z)
    

    输出

    ['A', 'B', 'C', 'D']
    ['0101', '0104', '0106', '0109']
    

    【讨论】:

      【解决方案3】:

      你可以使用 zip 功能来解决这个问题

      l = ['A','A','A','B','B','C','C','C','D']
      list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109']
      
      new_l = []
      new_list_date = []
      for i,j in zip(l,list_date):
          if i not in new_l:
              new_l.append(i)
              new_list_date.append(j)
      print(new_l)
      #['A', 'B', 'C', 'D']
      print(new_list_date)
      #['0101', '0104', '0106', '0109']
      
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-04
        • 2013-01-17
        • 1970-01-01
        • 2020-07-23
        • 1970-01-01
        • 2019-10-03
        • 1970-01-01
        • 2016-12-03
        相关资源
        最近更新 更多