【问题标题】:How to get duplicate strings of list with indices in Python如何在Python中获取带有索引的重复列表字符串
【发布时间】: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


【解决方案1】:

您可以按照以下方式做一些事情:

from collections import defaultdict

indeces = defaultdict(list)

for i, w in enumerate(my_list):
    indeces[w].append(i)

for k, v in indeces.items():
    if len(v) > 1:
        print(k, v)

of [5, 8, 21, 24, 30, 35]
a [6, 33, 48, 52]
are [12, 43]
with [14, 47]
noun [15, 26, 49, 53]
to [17, 50]
the [19, 22, 25, 28]

这使用collections.defaultdictenumerate 来有效地收集每个单词的索引。消除重复项仍然是一个简单的条件理解或使用 if 语句循环。

【讨论】:

  • 不,sample_listmy_list 仅区分大小写。
  • @SayandipDutta My bad 现在更新了所需的输出。
猜你喜欢
  • 2016-04-04
  • 2016-06-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 2018-05-17
相关资源
最近更新 更多