python - How to remove duplicate elements?
高洛峰
高洛峰 2017-06-28 09:24:47
0
2
789


For example, the first line above contains 3:19 and 3:6. How to write code so that the final file only takes the first one encountered? In this example, select 3:19

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
洪涛

Because I don’t know whether your string is a string or something, so I will implement it in the form of a string first

l = '0:13 1:9 2:14 3:19 4:12 3:19'
d = {}
result = []
for _ in l.split():
    key = _.split(':')[0]
    if key not in d:
        d[key] = _
        result.append(d[key])

print(result)
print(result)

# 输出
['0:13', '1:9', '2:14', '3:19', '4:12']
ringa_lee
from itertools import groupby

str = '0:13 1:9 2:14 3:19 4:12 3:6'
lst = str.split()
lst.sort()

g_lst = [list(g)[0] for k, g in groupby(lst, key=lambda x: x.split(':')[0])]
print g_lst

#['0:13', '1:9', '2:14', '3:19', '4:12']
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template