在列表中仅出现一次的单词的索引

时间:2018-07-07 08:57:11

标签: python string list indexing

我有以下单词列表:

x = ['Gaga', 'Gaga', 'Lam', 'Reem', 'Pal', 'Gaga','Lam']

我需要删除仅出现一次的单词,然后返回那里的索引或位置。

y = ['Gaga', 'Gaga', 'Lam', 'Gaga', 'Lam']

loc = [0, 0, 0, 1, 1, 0, 0]

有任何简单的功能可以做到这一点吗?

5 个答案:

答案 0 :(得分:3)

带有 pandas 模块及其pd.Series.duplicated()功能的单线

In [80]: x = ['Gaga', 'Gaga', 'Lam', 'Reem', 'Pal', 'Gaga','Lam']

In [81]: (~pd.Series(x).duplicated(keep=False)).astype(int).tolist()
Out[81]: [0, 0, 0, 1, 1, 0, 0]

要删除所有非重复项:

In [85]: s = pd.Series(x)

In [86]: s[s.duplicated(keep=False)].tolist()
Out[86]: ['Gaga', 'Gaga', 'Lam', 'Gaga', 'Lam']

答案 1 :(得分:1)

您可以为此目的使用Counter类:

from collections import Counter

x = ['Gaga', 'Gaga', 'Lam', 'Reem', 'Pal', 'Gaga','Lam']

c = Counter(x)

new_values = [item for item in x if c[item] > 1]
indexes = [1 if c[item] == 1 else 0 for item in x]

print(new_values)
print(indexes)

输出为:

['Gaga', 'Gaga', 'Lam', 'Gaga', 'Lam']
[0, 0, 0, 1, 1, 0, 0]

答案 2 :(得分:0)

您可以使用collections.Counter并隔离仅出现一次的项目。然后使用列表推导获得所需的结果。该解决方案虽然涉及3次通过,但总体上是O(n)。

x = ['Gaga', 'Gaga', 'Lam', 'Reem', 'Pal', 'Gaga','Lam']

from collections import Counter

singles = {k for k, v in Counter(x).items() if v == 1}

y = [i for i in x if i not in singles]
loc = [int(i in singles) for i in x]

print(y, loc, sep='\n')

['Gaga', 'Gaga', 'Lam', 'Gaga', 'Lam']
[0, 0, 0, 1, 1, 0, 0]

答案 3 :(得分:0)

您可以创建一个新列表并使用它吗?

return (n % 23 == 0)

答案 4 :(得分:0)

您还可以使用列表理解

x = ['Gaga', 'Gaga', 'Lam', 'Reem', 'Pal', 'Gaga', 'Lam'] 
y = [name for name in x if x.count(name) != 1]

输出

['Gaga','Gaga','Lam','Gaga','Lam']