【发布时间】:2021-02-10 12:01:31
【问题描述】:
我确实意识到这里已经解决了这个问题(例如,Removing duplicates in the lists)、Accessing the index in 'for' loops?、Append indices to duplicate strings in Python efficiently 等等......不过,我希望这个问题有所不同。
我几乎需要编写一个程序来检查列表是否有任何重复项,如果有,则返回重复的元素以及索引。
样本列表sample_list
sample = """An article is any member of a class of dedicated words that are used with noun phrases to
mark the identifiability of the referents of the noun phrases. The category of articles constitutes a
part of speech. In English, both "the" and "a" are articles, which combine with a noun to form a noun
phrase."""
sample_list = sample.split()
my_list = [x.lower() for x in sample_list]
len(my_list)
output: 55
获取唯一项目集合的常用方法是使用集合,集合将有助于去除重复项。
unique_list = list(set(my_list))
len(unique_list)
output: 38
这是我尝试过的,但老实说,我不知道下一步该做什么......
from functools import partial
def list_duplicates_of(seq,item):
start_at = -1
locs = []
while True:
try:
loc = seq.index(item,start_at+1)
except ValueError:
break
else:
locs.append(loc)
start_at = loc
return locs
dups_in_source = partial(list_duplicates_of, my_list)
for i in my_list:
print(i, dups_in_source(i))
这将返回所有具有索引和重复索引的元素
an [0]
article [1]
.
.
.
form [51]
a [6, 33, 48, 52]
noun [15, 26, 49, 53]
phrase. [54]
在这里,我只想返回重复元素及其索引,如下所示
of [5, 8, 21, 24, 30, 35]
a [6, 33, 48, 52]
are [12, 43]
with [14, 47]
.
.
.
noun [15, 26, 49, 53]
【问题讨论】:
-
您可能希望首先从
sample中删除任何不是字母或空格字符的内容。
标签: python string list indexing