Dbx
Dbx

Reputation: 5

How can I remove x multiple instances of same element from list?

I am fairly new to Python and am trying to write a text based game that uses card drawing from a deck of various cards including resource cards. I am trying to write code that enables user to trade in resources from their hand to do something else using lists. I've managed to accomplish this for if user trades 1 of each resource but am having trouble with if they want to trade 3 of same resource.

I searched here and on several different sites but they only say how to remove ALL of an instance of element in list. Referencing index in list eg. using pop or del, won't work because the cards in users hand is constantly changing in game.

resources = ["A","A","B","C","A","B"]

print(resources)

if "A" in resources and "B" in resources and "C" in resources:
    resources.remove("A")
    resources.remove("B")
    resources.remove("C")
else:
    print("You do not have 1 of each resource!")

print(resources)

for i in range(3):
    if "A" in resources:
        resources.remove("A")
    else:
        print("You do not have 3 of 'A' resource!")

print(resources)

This is not what I'm looking for as even if user doesn't have 3 of "A", it removes 2 of "A". I need some way of checking users hand to see if they've got 3 or more of "A" and if they haven't, don't remove any of "A". Hope this makes sense.

Upvotes: 0

Views: 454

Answers (2)

dmmfll
dmmfll

Reputation: 2836

This may be useful if you don't want to change the original list.

This will create a new list.

This code will remove all but 2 of any item where there are more than 2 of any item. I added four D's to demonstrate.

from collections import Counter

resources = ["A","A","B","C","A","B", *["D"] * 4]

list(''.join(item * 2 if count > 2 else item * count 
             for item, count in Counter(resources).items()))

Output: ['A', 'A', 'B', 'B', 'C', 'D', 'D']

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195553

You can use count() method of list:

resources = ["A","A","B","C","A","B"]

# check if user has 3+ "A"
if resources.count("A") > 2:
    # yes, remove 2 "A"s
    for i in range(2):
        resources.remove("A")

print(resources)

Prints:

['B', 'C', 'A', 'B']

Upvotes: 1

Related Questions