我有一个列表lst = [1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4]
我期待以下输出:
out = [1,"","",2,"","","",3,"","","","",4,"","","","","","","",""]
我想保留该项目的第一个匹配项,并用空字符串替换同一项目的所有其他匹配项。
我尝试了以下方法。
`def splrep(lst):
from collections import Counter
C = Counter(lst)
flst = [ [k,]*v for k,v in C.items()]
nl = []
for i in flst:
nl1 = []
for j,k in enumerate(i):
nl1.append(j)
nl.append(nl1)
ng = list(zip(flst, nl))
for i,j in ng:
j.pop(0)
for i,j in ng:
for k in j:
i[k] = ''
final = [i for [i,j] in ng]
fin = [i for j in final for i in j]
return fin`
但是我正在寻找一些更简单或更好的方法。
答案 0 :(得分:5)
答案 1 :(得分:2)
使用简单的迭代
例如:
start:
a = Console.ReadLine("Enter Command:");
goto start;
输出:
lst = [1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4]
dup_check = set()
result = []
for i in lst:
if i not in dup_check:
result.append(i)
dup_check.add(i)
else:
result.append("")
print(result)
答案 2 :(得分:1)
尝试以下简单功能:
def fill_blank(l):
filled = []
last = l[0]
for i in l:
if i != last:
last = i
filled.append(last)
return filled
以这种方式使用:
>>> lst = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4]
>>> out = fill_blank(lst)
>>> print(out)
[1, '', '', 2, '', '', '', 3, '', '', '', '', 4, '', '', '', '', '', '', '', '']
答案 3 :(得分:1)
如果您不想使用set
或itertools
,请执行以下操作:
lst = [1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4]
new_lst = []
for i in lst:
if i in new_lst:
new_lst.append("")
else:
new_lst.append(i)
print(new_lst)
输出:
[1, '', '', 2, '', '', '', 3, '', '', '', '', 4, '', '', '', '', '', '', '', '']
答案 4 :(得分:1)
不使用任何模块的简短解决方案(单行)如下:
lst = [1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4]
out = ["" if (i in lst[:inx]) else i for inx,i in enumerate(lst)]
print(out)
输出
[1, '', '', 2, '', '', '', 3, '', '', '', '', 4, '', '', '', '', '', '', '', '']
答案 5 :(得分:1)
您可以尝试以下方法。
lst = [1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4]
fin=[]
for each in lst:
if each not in fin:
fin.append(each)
else:
fin.append("")
print(fin)
答案 6 :(得分:1)
您可以使用dict.setdefault()
将第一个出现的词存储在字典中,然后根据找到的第一个出现的数字来保留它们:
lst = [1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,4,4,4]
first_indices = {}
for i, x in enumerate(lst):
first_indices.setdefault(x, i)
result = [x if first_indices[x] == i else "" for i, x in enumerate(lst)]
print(result)
# [1, '', '', 2, '', '', '', 3, '', '', '', '', 4, '', '', '', '', '', '', '', '']