[英]How can I find if a word (string) occurs more than once in an input/list in python
[英]In Python I want to code so that if user types a word that my list has more than once, both of the strings in the list get taken out
我希望有一個列表,如[“King S”,“King H”,“Ace S”,“4 C”]然后當被要求用戶輸入什么卡丟棄時,如果用戶寫國王,兩者都國王將從名單中刪除。
我剛剛開始編碼,到目前為止我已經制作了代碼,這樣如果你輸入像“King H”這樣的特定卡片,它就會從列表中刪除。
dropCard = input()
dropCardCapital = dropCard.title()
while dropCardCapital not in pOneCards:
print("You do not have the card " + dropCardCapital + ", please type a card that you have.")
dropCard = input()
dropCardCapital = dropCard.title()
if dropCardCapital in pOneCards:
print("You dropped " + dropCardCapital)
DCCC = Counter([dropCardCapital])
pOneCards = set(pOneCardsCounter - DCCC)
pOneCardsCounter = Counter(pOneCards)
pOneCards是我希望從中取出卡片的列表。 它檢查輸入是否在pOneCards中,如果它正在使用計數器,它會從pOneCards列表中減去您的輸入。 我想要發生的是,如果你的輸入為王,列表中有兩個國王都會被減去。
我也沒關系,而不是使每張卡片King H / King S只有四個“King”並且不指定顏色或套裝。
我創建了函數remove_card()
,您可以在其中僅使用值或使用值AND顏色指定卡:
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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.