def best_wild_hand(hand):
dictSuit = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':11, 'Q':12, 'K':13, 'A':14 }
listofLists = []
blackJoker = "?B"
list1 = [x + "S" for x in dictSuit]
index = len(hand)
if blackJoker in hand:
newHand = hand
newHand.remove(blackJoker)
for d in list1:
newHand.insert(index +1, d)
listofLists.append(newHand)
return listofLists
print best_wild_hand(['6C', '7C', '8C', '9C', 'TC', '5C', '?B'])我的输出应该在列表的格式列表中。我的代码似乎将列表中的每个元素都提供给newHand(也是list)。我只想要一个元素插入到newHand列表中,而newhand列表附加到listofLists中。我把它格式化如下
期望输出列表
[['6C', '7C', '8C', '9C', 'TC', '5C', '2S']
['6C', '7C', '8C', '9C', 'TC', '5C', '3S']
['6C', '7C', '8C', '9C', 'TC', '5C', '4S']
['6C', '7C', '8C', '9C', 'TC', '5C', '5S']
.
.
.
....................................'14S']]发布于 2015-01-29 01:48:04
您甚至不需要在hand列表中添加任何内容。这只会造成不必要的混乱。这似乎能做你想做的一切。
def best_wild_hand(hand):
dictSuit = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}
blackJoker = "?B"
cards = [x + "S" for x in dictSuit]
finalList = []
if blackJoker in hand:
hand.remove(blackJoker)
for c in cards:
finalList.append(hand + [c])
return finalList您还可以将其作为列表理解(并跳过通过立即返回结果来初始化finalList ):
if blackJoker in hand:
hand.remove(blackJoker)
return [hand + [c] for c in cards]请记住,像newHand = hand这样的代码,其中hand是一个列表,并不会创建原始列表的副本。因此,它在Python中是一个相当无用的赋值,因为修改newHand也会修改hand引用的原始数据,因为您处理的是可变对象(list)。
如果您不希望修改原始列表,可以通过以下方式复制它:
import copy
# Now when you modify newHand (i.e appending or removing items)
# the original hand list from the caller's frame will not be affected.
newHand = copy.copy(hand)
# You can alternatively copy the list using...
newHand = hand[:]
# However, if there are other mutable objects inside of `hand` you wished
# to copy, you'd have to use the `deepcopy` method of `copy`.发布于 2015-01-29 01:50:46
我认为在代码执行之后,listofLists将是:
[newHand, newHand, newHand, ..., newHand]但是每次循环处理时,newHand都会改变,最后,listOfList将包含许多相同的newHand。您可以这样编写循环块:
if blackJoker in hand:
curHand = hand
curHand.remove(blackJoker)
for d in list1:
newHand = curHand[:-1]
newHand.insert(index +1, d)
print newHand
listofLists.append(newHand)
return listofLists发布于 2015-01-29 01:44:43
首先,检查您的缩进--很难理解if和for里面是什么。以下是我对你的目标的最佳猜测:
def best_wild_hand(hand):
dictSuit = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}
result = []
blackJoker = "?B"
cardList = [x + "S" for x in dictSuit]
index = len(hand)
if blackJoker in hand:
hand.remove(blackJoker)
for card in cardList:
result.append(hand + [card])
return resultappend可以用于将一个元素放在python列表的末尾,并且比在末尾插入一个元素要干净得多。
https://stackoverflow.com/questions/28205504
复制相似问题