[英]How do I put a string in a list at every nth index?
I'm working on a function that gets the suit and value as a string in a list from another function: 我正在研究一个函数,该函数将从另一个函数以列表中的字符串形式获取西装和值:
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
With the new function it is to take the information from the above function and return it in a list with a certain structure "VALUE of SUIT". 使用新功能时,将从上述功能中获取信息,并将其返回到具有特定结构“ SUIT的值”的列表中。
So say if you had "3", "Spades" it would return "3 of Spades" instead. 假设您有“ 3”,“ Spades”,它将返回“ 3 of Spades”。
This is my code so far on the new function. 到目前为止,这是我在新功能上的代码。
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]))]
My question is, is how do I insert "of" between the value and suit without having to do .join a million times? 我的问题是,我如何在值和西装之间插入“ of”而不必做一百万次?
You can do it in your for
loop 您可以在
for
循环中进行操作
for n in myList:
hand += [" of ".join(getCard(n))]
return hand
You can also do it in getCard
and return '3 of Spades'
您也可以在
getCard
执行此getCard
并返回'3 of Spades'
BTW: you could keep it as tuples on list 顺便说一句:您可以将其作为元组保留在列表中
hand = [ ("3", "Spades"), ("Queen", "Spades"), ... ]
then you can use for
loop instead of slices [:2]
, [2:4]
那么您可以使用
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
If you use a list of tuple you can do with format and list comprehension 如果您使用元组列表,则可以使用格式和列表理解
test_hand = [("3","space"),("4","old")]
return ["{} of {}".format(i,z) for i,z in (test_hand)]
output: 输出:
['3 of space', '4 of old']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.