我有一个列表
carner_list = ['<a href="/lyric/34808442/Loyle+Carner/Damselfly">Damselfly</a>',
'<a href="/lyric/37311114/Loyle+Carner/Damselfly">Damselfly</a>',
'<a href="/lyric/37360958/Loyle+Carner/Damselfly">Damselfly</a>',
'<a href="/lyric/33661937/Loyle+Carner/The+Isle+of+Arran">The Isle of Arran</a>',
'<a href="/lyric/33661936/Loyle+Carner/Mean+It+in+the+Morning">Mean It in the Morning</a>']
现在我想摆脱重复的项目。问题是,double 项仅在字符串中的特定点 i[38:] 彼此不同。
我的想法是创建一个 for 循环:
new_list = []
for i in carner_list:
if i[38:] in new_list:
print("found")
else:
new_list = new_list + [i]
print("not")
但这行不通。
是语法错误还是我完全走错了路?
最佳拉塞尔
最佳答案
我输入了一个名为 listContains
的小函数,我认为它可以解决您的问题。您的代码不起作用,因为您在 new_list
中搜索值 i[38:]
,而在 new_list
中您附加了整个值我
。
因此,您还应该对列表的每个值应用 [38:] 规则。
我认为下面的代码可以更好地解释我在说什么:
carner_list = ['<a href="/lyric/34808442/Loyle+Carner/Damselfly">Damselfly</a>',
'<a href="/lyric/37311114/Loyle+Carner/Damselfly">Damselfly</a>',
'<a href="/lyric/37360958/Loyle+Carner/Damselfly">Damselfly</a>',
'<a href="/lyric/33661937/Loyle+Carner/The+Isle+of+Arran">The Isle of Arran</a>',
'<a href="/lyric/33661936/Loyle+Carner/Mean+It+in+the+Morning">Mean It in the Morning</a>']
new_list = []
def listContains(myList, toSearch):
for val in myList:
if val[38:] == toSearch:
return True
return False
for i in carner_list:
if listContains(new_list, i[38:]):
print("found")
else:
new_list.append(i)
print("not")
print(new_list)
如果你想测试它,你可以从 here 开始
关于python - 从列表中创建一个新列表但没有重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63674944/