如何将单词添加到小列表值

list=["Book","Glass","Book,"Watch","Doll,"Book"]

def a_list(list)

输出:


The List is:

Book

Glass

Book

Watch

Doll

Book

检查后的清单:


Book

Glass unique

Book

Watch unique

Doll unique

Book


蛊毒传说
浏览 124回答 2
2回答

ITMISS

您可以简单地使用collections.Counter来检测计数不超过 1 的唯一项目。from collections import Counterlst=["Book","Glass","Book","Watch","Doll","Book"]def a_list(items):    # Count the words    counts = Counter(items)    for item in items:        # Found a non-unique item, don't add "unique" to it        if counts[item] > 1:            print(item)        # Found a unique item, add "unique" to it        else:            print(item, "unique")a_list(lst)输出:BookGlass uniqueBookWatch uniqueDoll uniqueBook我们还可以将这些项目附加到一个新列表并返回它:def a_list(items):    counts = Counter(items)    result = []    for item in items:        if counts[item] > 1:            result.append(item)        else:            result.append(f"{item} unique")    return resultprint(a_list(lst))或使用列表理解:def a_list(items):    counts = Counter(items)    return [item if counts[item] > 1 else f"{item} unique" for item in items]print(a_list(lst))输出:['Book', 'Glass unique', 'Book', 'Watch unique', 'Doll unique', 'Book']

暮色呼如

一个简单的方法是:ll=["Book","Glass","Book","Watch","Doll","Book"]def a_list(l):    for elem in l:        if l.count(elem) > 1:            print(elem)        else:            print(elem, "unique")a_list(ll)这将提供所需的输出。如果你想改变列表并返回它,应该使用相同的逻辑,但你应该改变元素本身,而不是打印,如下所示:ll=["Book","Glass","Book","Watch","Doll","Book"]def a_list(l):    for i, elem in enumerate(l):        if l.count(elem) > 1:            l[i] = "{:} unique".format(elem)    return llll = a_list(ll)print(lll)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python