【问题标题】:How do I put a string in a list at every nth index?如何在每个第 n 个索引处将字符串放入列表中?
【发布时间】:2016-10-09 01:56:46
【问题描述】:

我正在开发一个函数,该函数将西装和值作为字符串从另一个函数的列表中获取:

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

使用新函数,它是从上述函数中获取信息并将其返回到具有特定结构“西装价值”的列表中。

所以说如果你有“3”,“黑桃”它会返回“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”而不必执行 .join 一百万次?

【问题讨论】:

  • 请修正你的缩进
  • @IronFist 已修复
  • 你还没有修复第一部分

标签: python list python-3.x join


【解决方案1】:

您可以在 for 循环中进行操作

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

return hand

您也可以在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

【讨论】:

  • 如果我需要一张以上的卡怎么办?即使列表中有 4 个整数,将其放入循环中也只会返回一张卡片。
  • 不,它会给您 4 张卡片,因为您不会在第一张卡片后离开 for 循环
  • 您可以将第二个示例缩短为:new_list = [' of '.join(card) for card in hand]
  • @leaf 是的,我知道,但是对于像 OP 这样的初学者来说,更长的版本应该更易读。
  • @furas 我在任何地方都没有看到 OP 说他是初学者,你在拉我的腿吗 ;)
【解决方案2】:

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

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

输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-24
    • 2020-09-02
    • 2022-01-15
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多