如何将列表项设置为特定变量?

时间:2017-04-16 03:04:11

标签: 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。我知道这可能是毫无意义和不必要的(我读过人们告诉他不要的其他帖子),但我的想法不仅仅是获取信息来完成程序,还要学习如何按照要求的方式去做。如果它确实太麻烦了,我可能会废弃这个变量,但是对此问题的任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:2)

<?php $output = (isset($_POST['mmm'])) ? $_POST['mmm'] : 0; if($output !== 0) { echo "SUCCESS: Thanks for submitting value=". $output." Something:".$_POST['something'] ; die; } ?> <html> <head> <title>Test</title> <script src="jquery.min.js"></script> <script> function submitData() { var somethingVal = $("#something").val(); $.ajax({ type: "POST", url: 'http://localhost/app.php', data: {mmm: 145, something: somethingVal}, success: function(data){ $("#message").html(data); } }); //document.getElementById("adminLoginForm").submit(); //Stop form submission return false; } </script> </head> <body> <div id="message"></div> <form method="post" id="adminLoginForm" onsubmit="return submitData()"> <input type="text" value="Something" name="something" id="something"/> <input type="submit" value="Submit"/> </form> </body> </html> 更改了列表,即它不会返回任何内容,它只会改变现有列表。要解决此问题,您可以执行以下操作:

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

答案 1 :(得分:1)

random.shuffle就地工作,这意味着TheList现已改组,None将返回TheShownCards。这意味着当您尝试获取元素0时,您会拨打相当于None.__getitem__(0)的调用,该调用不存在。只需从TheChosenCard中选择元素0即可TheList