python - 如何将列表中的项目设置为特定变量?

标签 python python-2.7 list variables

我正在尝试使用 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/

相关文章:

python - 使用 strftime 格式化字典中的 datetime.timedelta 对象

c# - 来自 Enumerable.FromRange().Select() 与 ToList() 的 IEnumerable<T>

python - 如何在 Python 中将一个列表拆分为两个唯一列表?

python - AWS Lambda 记录到一个 JSON 行

python - OpenCV:用轮廓上的大多数点拟合椭圆(而不是最小二乘法)

python - 如何使用 lxml 获取元素

python - 从fasta序列制作表格,python

python - 如何使用 pandas python 合并数据帧?

python - 比较两个 Pandas 数据框的差异

c - C 中的字符串动态分配