一次只出现一次的单词索引

2024-09-28 16:58:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下单词列表:

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

我需要删除只出现一次的单词,然后返回索引或位置。你知道吗

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

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

有什么简单的函数可以做到这一点吗?你知道吗


Tags: 函数列表单词locpallamgagareem
3条回答

具有pandas模块及其^{}函数的可选的一个线性

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']

您可以使用^{}并隔离只出现一次的项。然后用列表理解你想要的结果。解决方案总体上是O(n),尽管它涉及3个过程。你知道吗

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]

您可以使用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]

相关问题 更多 >