Python-在保留索引的同时删除重复元素
我有两个清单,如:Python-在保留索引的同时删除重复元素,python,list,duplicates,Python,List,Duplicates,我有两个清单,如: x = ['A','A','A','B','B','C','C','C','D'] list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109'] 我想删除列表中重复的元素,它可以通过中的答案来实现 然而,我期望的结果是 ['A','B','C','D'] ['0101','0104','0106','0109'] 就是 对于x,我想删除重复的元素 对于list_date,我希望根据
x = ['A','A','A','B','B','C','C','C','D']
list_date = ['0101','0102','0103','0104','0105','0106','0107','0108','0109']
我想删除列表中重复的元素,它可以通过中的答案来实现
然而,我期望的结果是
['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']
我应该如何处理这样的列表?您可以使用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']
请参见下面的尝试:
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']
你可以使用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']
那么您想从
列表\u date
中删除从x
中删除的位置吗?如果您的数据是链接的,是否有理由使用两个列表而不是一个字典?