Python 如何在每N个索引处将字符串放入列表中?

Python 如何在每N个索引处将字符串放入列表中?,python,list,python-3.x,join,Python,List,Python 3.x,Join,我正在处理一个函数,该函数将西服和值作为一个字符串从另一个函数的列表中获取: 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:

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

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

我的问题是,我如何在值和西装之间插入“of”,而不必这样做。加入一百万次?

您可以在
for
循环中这样做

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

return hand
您还可以在
getCard
中执行此操作,并返回
'3 of Spades'


顺便说一句:你们可以把它作为元组保存在列表中

hand = [ ("3", "Spades"), ("Queen", "Spades"), ... ]
然后,您可以使用
进行
循环,而不是使用切片
[:2]
[2:4]

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

return new_list

您可以在
for
循环中执行此操作

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

return hand
您还可以在
getCard
中执行此操作,并返回
'3 of Spades'


顺便说一句:你们可以把它作为元组保存在列表中

hand = [ ("3", "Spades"), ("Queen", "Spades"), ... ]
然后,您可以使用
进行
循环,而不是使用切片
[: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']

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

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

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

请把你的头发修好indentation@IronFist你还没修好第一部分请修好你的indentation@IronFist你还没修好第一部分如果我需要一张以上的卡怎么办?即使我在列表中有4个整数,将其放入循环中也只会返回一张卡。不,它会给你4张卡,因为你不会在第一张卡之后离开
for
循环。你可以将第二个示例缩短为:
new\u list=['of'。加入(卡)以获得手中的卡]
@leaf是的,我知道,但较长的版本应该更适合像OP这样的初学者阅读。@furas我看不到OP说他是初学者的地方,你在开我玩笑吗;)如果我需要不止一张卡怎么办?即使我在列表中有4个整数,将其放入循环中也只会返回一张卡。不,它会给你4张卡,因为你不会在第一张卡之后离开
for
循环。你可以将第二个示例缩短为:
new\u list=['of'。加入(卡)以获得手中的卡]
@leaf是的,我知道,但较长的版本应该更适合像OP这样的初学者阅读。@furas我看不到OP说他是初学者的地方,你在开我玩笑吗;)