为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蛊毒传说 2022-11-01 16:14:26
list=["Book","Glass","Book,"Watch","Doll,"Book"]def a_list(list)输出:The List is:BookGlassBookWatchDollBook检查后的清单:BookGlass uniqueBookWatch uniqueDoll uniqueBook
查看完整描述

2 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

您可以简单地使用collections.Counter来检测计数不超过 1 的唯一项目。


from collections import Counter


lst=["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)

输出:


Book

Glass unique

Book

Watch unique

Doll unique

Book

我们还可以将这些项目附加到一个新列表并返回它:


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 result


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


查看完整回答
反对 回复 2022-11-01
?
暮色呼如

TA贡献1853条经验 获得超9个赞

一个简单的方法是:


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 l


lll = a_list(ll)

print(lll)


查看完整回答
反对 回复 2022-11-01
  • 2 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信