簡體   English   中英

如何在每個第n個索引處將字符串放入列表中?

[英]How do I put a string in a list at every nth index?

我正在研究一個函數,該函數將從另一個函數以列表中的字符串形式獲取西裝和值:

def getCard(n):
    deckListSuit = []
    grabSuit = getSuit(n)
    n = (n-1) % 13 + 1
    if n == 1:
        deckListSuit.append("Ace")
        return deckListSuit + grabSuit
    if 2 <= n <= 10:
        deckListSuit.append(str(n))
        return deckListSuit + grabSuit
    if n == 11:
        deckListSuit.append("Jack")
        return deckListSuit + grabSuit
    if n == 12:
        deckListSuit.append("Queen")
        return deckListSuit + grabSuit
    if n == 13:
        deckListSuit.append("King")
        return deckListSuit + grabSuit

使用新功能時,將從上述功能中獲取信息,並將其返回到具有特定結構“ SUIT的值”的列表中。

假設您有“ 3”,“ Spades”,它將返回“ 3 of Spades”。

到目前為止,這是我在新功能上的代碼。

def getHand(myList):
    hand = []
    for n in myList:
        hand += getCard(n)
    return [(" of ".join(hand[:2]))] + [(" of ".join(hand[2:4]))] + [(" of ".join(hand[4:6]))] + [(" of ".join(hand[6:8]))] + [(" of ".join(hand[8:10]))]

我的問題是,我如何在值和西裝之間插入“ of”而不必做一百萬次?

您可以在for循環中進行操作

for n in myList:
    hand += [" of ".join(getCard(n))]

return hand

您也可以在getCard執行此getCard並返回'3 of Spades'


順便說一句:您可以將其作為元組保留在列表中

hand = [ ("3", "Spades"), ("Queen", "Spades"), ... ]

那么您可以使用for循環而不是切片[:2][2:4]

new_list = []
for card in hand: 
    # in `card` you have ("3", "Spades")
    new_list.append(' of '.join(card))

return new_list

如果您使用元組列表,則可以使用格式和列表理解

test_hand = [("3","space"),("4","old")]
return ["{} of {}".format(i,z) for i,z in (test_hand)]

輸出:

 ['3 of space', '4 of old']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM