![](/img/trans.png)
[英]How to remove duplicates, by sublist item subset, in a list of lists in Python?
[英]Remove duplicates in a list of lists based on the third item in each sublist
我有一个列表列表,看起来像:
c = [['470', '4189.0', 'asdfgw', 'fds'],
['470', '4189.0', 'qwer', 'fds'],
['470', '4189.0', 'qwer', 'dsfs fdv']
...]
c
有大约30,000个内部列表。 我想做的是根据每个内部列表的第4个项目消除重复项。 因此,上面的列表列表如下所示:
c = [['470', '4189.0', 'asdfgw', 'fds'],['470', '4189.0', 'qwer', 'dsfs fdv'] ...]
这是我到目前为止的内容:
d = [] #list that will contain condensed c
d.append(c[0]) #append first element, so I can compare lists
for bact in c: #c is my list of lists with 30,000 interior list
for items in d:
if bact[3] != items[3]:
d.append(bact)
我认为这应该可行,但它会不断运行。 我让它运行30分钟,然后将其杀死。 我认为程序不会花这么长时间,所以我猜我的逻辑有问题。
我觉得创建一个全新的列表列表非常愚蠢。 任何帮助将不胜感激,请随时随地学习。 如果不正确,请更正我的词汇。
我会这样:
seen = set()
cond = [x for x in c if x[3] not in seen and not seen.add(x[3])]
说明:
seen
一个集合,该集合跟踪每个子列表中已经遇到的第四个元素。 cond
是简要列表。 如果未seen
x[3]
(其中x
是c
的子列表),则将x
添加到cond
并将x[3]
添加到seen
。
seen.add(x[3])
将返回None
,所以not seen.add(x[3])
将始终是True
,但是这仅仅部分将被评估,如果x[3] not in seen
是True
,因为Python使用短电路评估。 如果第二个条件得到评估,它将始终返回True
并具有将x[3]
添加到seen
的副作用。 这是正在发生的事情的另一个示例( print
返回None
并且具有打印某些东西的“副作用”):
>>> False and not print('hi')
False
>>> True and not print('hi')
hi
True
您当前的代码中存在一个明显的逻辑缺陷:
for items in d:
if bact[3] != items[3]:
d.append(bact)
这增加了bact
到d
一次在每个项目d
不匹配 。 要获得最低限度的修复,您需要切换到:
for items in d:
if bact[3] == items[3]:
break
else:
d.append(bact)
如果d
所有项目都不匹配,则添加一次bact
。 我怀疑这将意味着您的代码在更合理的时间内运行。
最重要的是,一个显着的性能提升(提升速度,虽然在内存使用成本)将是保持一个set
到目前为止,您已经看到了第四个元素。 集合上的查找使用哈希,因此隶属度测试(突出显示)将更快。
d = []
seen = set()
for bact in c:
if bact[3] not in seen: # membership test
seen.add(bact[3])
d.append(bact)
使用大熊猫。 我认为您也有更好的列名。
c = [['470', '4189.0', 'asdfgw', 'fds'],
['470', '4189.0', 'qwer', 'fds'],
['470', '4189.0', 'qwer', 'dsfs fdv']]
import pandas as pd
df = pd.DataFrame(c, columns=['col_1', 'col_2', 'col_3', 'col_4'])
df.drop_duplicates('col_4', inplace=True)
print df
col_1 col_2 col_3 col_4
0 470 4189.0 asdfgw fds
2 470 4189.0 qwer dsfs fdv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.