如何修复“ TypeError:类型'NoneType'的对象没有len()”?

时间:2019-04-01 16:36:20

标签: python list methods

我目前正在学校为计算机科学原理课尝试用Python编写Uno,我创建了一个定义,将卡片组中的纸牌抽到玩家的手中,每当我运行代码时,我都会不断遇到此错误。我只是想知道如何解决它,因为我尝试了几件事却一无所获。

我尝试将物品添加到玩家的手上(开始为空)。 我尝试使用元组。我尝试使用将绘图变量设为列表。 x规定了哪位玩家的手牌,y是他们抽出的手数,z是卡片组中的牌。

import random
import time
import sys

def draw_cards(x,y,z):
  for q in range(y):
    draw = random.choice(z)
    x = x.insert(0,draw)
    z = z.remove(draw)
  return x,z

cards_in_deck = ["red 0","red 1", "red 2", "red 3", "red 4", "red 5","red 6","red 7", "red 8", "red 9", "red skip", "red reverse","red +2","wild","yellow 0","yellow 1", "yellow 2", "yellow 3", "yellow 4", "yellow 5","yellow 6","yellow 7", "yellow 8", "yellow 9", "yellow skip", "yellow reverse","yellow +2","wild","green 0","green 1", "green 2", "green 3", "green 4", "green 5","green 6","green 7", "green 8", "green 9", "green skip", "green reverse","green +2","wild","blue 0","blue 1", "blue 2", "blue 3", "blue 4", "blue 5","blue 6","blue 7", "blue 8", "blue 9", "blue skip", "blue reverse","blue +2","wild","red 1", "red 2", "red 3", "red 4", "red 5","red 6","red 7", "red 8", "red 9", "red skip", "red reverse","red +2","wild +4","yellow 1", "yellow 2", "yellow 3", "yellow 4", "yellow 5","yellow 6","yellow 7", "yellow 8", "yellow 9", "yellow skip", "yellow reverse","yellow +2","wild +4","green 1", "green 2", "green 3", "green 4", "green 5","green 6","green 7", "green 8", "green 9", "green skip", "green reverse","green +2","wild +4","blue 1", "blue 2", "blue 3", "blue 4", "blue 5","blue 6","blue 7", "blue 8", "blue 9", "blue skip", "blue reverse","blue +2","wild +4"]

player_hand = []
ai_dusty_hand = []
ai_cutie_hand = []
ai_smooth_hand= []

draw_cards(ai_dusty_hand,7,cards_in_deck)
draw_cards(ai_cutie_hand,7,cards_in_deck)
draw_cards(ai_smooth_hand,7,cards_in_deck)
draw_cards(player_hand,7,cards_in_deck)

我希望结果是每个玩家都有起手牌,但是输出以错误结束,

2 个答案:

答案 0 :(得分:1)

Python中的列表是可变的。因此,当您操作一个列表(即使在函数范围内)时,它也会在引用该列表的任何地方反映出来。

x = x.insert(0,draw)
z = z.remove(draw)

这些代码行指定列表中方法调用的返回。这两个方法调用均不返回任何内容(因此它们返回None)。

删除函数中列表的分配。

答案 1 :(得分:0)

问题出在这两行,因为remove不会返回列表:

x = x.insert(0, draw)
z = z.remove(draw)

insertremove不返回任何内容。不要重新分配xz,它应该可以工作:

x.insert(0, draw)
z.remove(draw)

此外,您应该返回z来保存剩余的卡:

def draw_cards(x,y,z):
  for q in range(y):
    draw = random.choice(z)
    x.insert(0,draw)
    z.remove(draw)
return z

cards_in_deck = draw_cards(ai_dusty_hand,7,cards_in_deck)
cards_in_deck = draw_cards(ai_cutie_hand,7,cards_in_deck)
cards_in_deck = draw_cards(ai_smooth_hand,7,cards_in_deck)
cards_in_deck = draw_cards(player_hand,7,cards_in_deck)