我从一个txt文件中取出了40个单词的列表。我找到了重复的词,并用相同的词替换了它们,但前后都用“*”代替。代码如下:
def show(self, list1):
a = [x for x in list1 if list1.count(x) > 1]
lista2 = ["*"+s+"*" if s in a else s for s in list1]
print(lista2)
输入:
^{pr2}$输出:
> ['utanför', 'dörren', 'stod', 'en', 'man', '*och*', 'lyssnade', 'intensivt', '*i*', 'den', 'mörka', 'korridoren', '*han*', 'hade', 'skuggat', 'digby', 'groat', 'hela', 'eftermiddagen', '*och*', 'följt', 'efter', 'honom', '*in*', '*i*', 'huset', 'när', '*han*', 'fick', 'hära', 'ljudet', 'av', 'fotsteg', 'från', 'rummet', 'smög', '*han*', 'sig', '*in*', '*i*']
请注意,副本的前面和后面都有一个*
。在
我希望第一个副本被忽略,其余的在前面和后面用*突出显示。在
编辑:
def show(self, list1): new_list, seen = [], set() for x in list1: if x in seen: new_list.append('*{0}*'.format(x)) else: new_list.append(x) seen.add(x) print new_list
看起来很有魅力。 现在我唯一想补充的是使它区分大小写。好像“汉”和“汉”发生了,它注意到它是一个复制品。在
如果元素出现在切片列表中,则迭代并将其替换为星号版本。使用
enumerate
跟踪当前索引使用
set
来跟踪看到的项目:使用生成器函数:
^{pr2}$相关问题 更多 >
编程相关推荐