在Python中,我想编写这样的代码:如果用户多次键入我的列表中包含的单词,那么列表中的两个字符串都会被占用

2024-10-01 09:17:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一个类似于[“国王S”,“国王H”,“王牌S”,“4 C”] 然后,当要求用户输入要放在哪张卡上时,如果用户写了king,两个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,并且列表中有两个king,那么两个king都会被减去

我也同意,不是让每张卡都有四个“大号”而不是指定颜色或适合它


Tags: 用户inyou列表inputtitlehavenot
1条回答
网友
1楼 · 发布于 2024-10-01 09:17:09

我创建了函数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']

相关问题 更多 >