我正在尝试使用 Python 和 Powershell 的组合来编写纸牌戏法(我很清楚可以使用 Python 或 Powershell 来完成,但我想同时使用这两种语言进行练习反正)。在执行该技巧的 Python 部分时,我遇到了关于 NoneType
没有属性 __getitem__
的错误。我想我在这里找到了这个问题的答案TypeError: 'NoneType' object has no attribute '__getitem__'但我并不真正理解答案的含义(我仍然是这方面的初学者)。另外,我发现了另一个问题,有人试图做我正在做的事情( How to assign each element of a list to a separate variable? ),但该帖子中的每个人都只是说他所做的事情是不必要的,而不是给出答案。本质上,我想做他正在尝试的事情,除了第一个变量。
这是我的代码:
from random import shuffle
TheList = ["Ace of Spades", "Three of Hearts", "Five of Diamonds", "Seven of Clubs", "Nine of Spades", "Jack of Hearts", "King of Diamonds", "Two of Clubs", \
"Four of Spades", "Six of Hearts", "Eight of Diamonds", "Ten of Clubs"]
TheShownCards = shuffle(TheList)
TheChosenCard = TheShownCards[0]
print TheShownCards
print TheChosenCard
这是我收到的错误:
TypeError: 'NoneType' object has no attribute '__getitem__'
最后的print
命令仅用于调试,一旦完成脚本我将删除它们。本质上,我试图将列表 TheShownCards
的第一项保存为变量 TheChosenCard
。我知道这可能是毫无意义和不必要的(我读过其他帖子,人们告诉他不要这样做),但我在这里的想法不仅仅是获取完成程序的信息,而且还要学习如何 按照要求的方式进行。如果事实证明这确实太麻烦了,我可能会废弃该变量,但对此事的任何帮助将不胜感激。
最佳答案
shuffle
就地更改列表,即它不返回任何内容,它只是对现有列表进行洗牌。要解决此问题,您可以执行以下操作:
from random import shuffle
TheShownCards = ["Ace of Spades", "Three of Hearts", "Five of Diamonds", "Seven of Clubs", "Nine of Spades", "Jack of Hearts", "King of Diamonds", "Two of Clubs", "Four of Spades", "Six of Hearts", "Eight of Diamonds", "Ten of Clubs"]
shuffle(TheShownCards)
TheChosenCard = TheShownCards[0]
print TheShownCards
print TheChosenCard
返回:
['Jack of Hearts', 'Four of Spades', 'Seven of Clubs', 'Ace of Spades', 'Nine of Spades', 'Eight of Diamonds', 'Ten of Clubs', 'Five of Diamonds', 'King of Diamonds', 'Two of Clubs', 'Three of Hearts', 'Six of Hearts']
Jack of Hearts
这表明 TheShownCards
列表已被打乱,并且 TheShownCards
列表中的第一个元素已保存到 TheChosenCard
关于python - 如何将列表中的项目设置为特定变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43433287/