简体   繁体   中英

Remove or change SPECIFIC repeated elements of a list (not all repeated elements)

I'm trying to make something that can read through a list of character elements and tell you exactly how many times each element was repeated. My idea was to go through the list using a for loop and printing statements that tell me the info I want.

This was my first idea:

list = ["code", "this", "code"]

for i in range(len(list)):
    list.count(list[i])
    print("{} is repeated ".format(list[i]) + str(list.count(list[i])) + " times")

When I ran this code it printed:

code is repeated 2 times

this is repeated 1 times

code is repeated 2 times

Now, the next step towards my goal would be to to stop "code is repeated 2 times" from printing twice. This is were my troubles begin. I've searched for ways to remove specific duplicates from lists but all I've found is way to remove ALL duplicates (which I don't want since that would make the code useless after it goes past the first element of the list). Therefore, my questions are the following:

Would it be possible to remove specific repeated elements from the list once the statement of repetitions is printed? This would mean, once it prints "code is repeated 2 times", the list changes to ["this"] only.

Would it instead be possible to change the "values" of a specific repeated element? This would mean, once it prints "code is repeated 2 times", the list would change (for example) to [0, "this", 0] so that I could use an if statement to not print anything if the element is == 0.

To be clear, I just want to know:

-if it is possible: how could I change my coding to have that happen.

-if it is not possible: other things I might be able to do to reach my goals.

Useset :

lst = ["code", "this", "code"]
for elem in sorted(set(lst), key = lambda x:lst.index(x)):
    print(f"{elem} is repeated {lst.count(elem)} times")

Or, dict.fromkeys :

for elem in dict.fromkeys(lst):
    print(f"{elem} is repeated {lst.count(elem)} times")

Output:

code is repeated 2 times
this is repeated 1 times

You can also look at collections.Counter() :

from collections import Counter
frequency = Counter(lst)
for word, freq in frequency.items():
    print(f"{word} is repeated {freq} times")

Same output.

What you are saying is also possible in some sense, but it does not look pythonic, neither do I find it necessary, however here is the code.

CAUTION : Modifying the list while iterating over it is a bad idea.

lst = ['code', 'this', 'code']
i = 0
while any(lst):
    if lst[i] == None:
        i += 1
        continue
    print(f"{lst[i]} is repeated {lst.count(lst[i])} times")
    lst = [None if j == lst[i] else j for j in lst]
    i += 1

Output same.

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