简体   繁体   中英

How to add a word to a small list value

list=["Book","Glass","Book,"Watch","Doll,"Book"]
def a_list(list)

output:

The List is:
Book
Glass
Book
Watch
Doll
Book

The List after Check:

Book
Glass unique
Book
Watch unique
Doll unique
Book

A simple approach to do so is:

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)

This will give the desired output.

If you want to alter the list and return it, the same logic should be used but instead of printing you should change the element itself as follows:

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)

You can simply use collections.Counter to detect unique items that don't have a count more than 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)

Output:

Book
Glass unique
Book
Watch unique
Doll unique
Book

We can also append these items to a new list and return that as well:

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))

Or using a list comprehension :

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))

Output:

['Book', 'Glass unique', 'Book', 'Watch unique', 'Doll unique', 'Book']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM