【问题标题】:How to set items of a list to a specific variable?如何将列表项设置为特定变量?
【发布时间】:2017-09-11 23:56:12
【问题描述】:

我正在尝试使用 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。我知道这可能是没有意义和不必要的(我读过其他人告诉他不要这样做的帖子),但我在这里的想法不仅仅是获取信息以完成程序,而且还学习如何 按照要求的方式进行。如果确实证明太麻烦,我可能会放弃该变量,但对于此事的任何帮助将不胜感激。

【问题讨论】:

    标签: python python-2.7 list variables


    【解决方案1】:

    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

    【讨论】:

    • 不客气。如果它解决了您的问题,请接受答案。
    【解决方案2】:

    random.shuffle 就地工作,这意味着 TheList 现在被打乱,None 返回到 TheShownCards。这意味着当您尝试获取元素 0 时,您会进行相当于 None.__getitem__(0) 的调用,但它并不存在。只需将TheChosenCard 设为从TheList 中选择元素0 的结果即可。

    【讨论】:

      猜你喜欢
      • 2015-10-31
      • 2021-12-19
      • 2014-08-09
      • 2021-11-07
      • 2021-07-15
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多