Я сделал функцию remove_card()
, где вы можете указать карту только по значению или по значению И цвет:
from collections import defaultdict
lst = ["King S", "King H", "Ace S", "4 C"]
def remove_card(card, lst):
d = defaultdict(list)
s = ' '.join(lst).split()
for value, color in zip(s[::2], s[1::2]):
d[value.lower()].append(color.lower())
value, color = map(str.lower, card.split() if ' ' in card else (card, ''))
dropped = []
if value in d and color == '' and len(d[value]) > 1:
# remove all cards of certain value only if color is unspecified and we have
# more than one card of this value
dropped = [(value + ' ' + v).title() for v in d[value]]
del d[value]
elif value in d and color != '' and color in d[value]:
# color is specified and we have this card, remove it
dropped = [(value + ' ' + color).title()]
d[value].remove(color)
# convert back defaultdict to list
return [(k + ' ' + c).title() for k, v in d.items() for c in v], dropped
print('Initial list: ', lst)
lst, dropped = remove_card('ace', lst) # no card is removed - we have only one Ace
print('After trying to remove "ace": ', lst)
print('We dropped: ', dropped)
lst, dropped = remove_card('ace s', lst) # Ace S is removed - color is specified
print('After trying to remove "ace s": ', lst)
print('We dropped: ', dropped)
lst, dropped = remove_card('king', lst) # all 'kings' are removed, because we have more than one king
print('After trying to remove "king": ', lst)
print('We dropped: ', dropped)
Отпечатки:
Initial list: ['King S', 'King H', 'Ace S', '4 C']
After trying to remove "ace": ['King S', 'King H', 'Ace S', '4 C']
We dropped: []
After trying to remove "ace s": ['King S', 'King H', '4 C']
We dropped: ['Ace S']
After trying to remove "king": ['4 C']
We dropped: ['King S', 'King H']