1

私はPythonで辞書を試してきたので、参照されていると思うので「マジックナンバー」を削除できますが、エラーが発生し続けます:タイプ「NoneType」のオブジェクトにはlen()がありません。私の絞首刑執行人プログラムで時々発生するだけで、その理由はわかりません。これは、クラッシュすると思われる一般的な領域です。

animals = 'ape bear beaver cat donkey fox goat llama monkey python bunny tiger wolf'.split()
colors = 'yellow red blue green orange purple pink brown black white gold'.split()
adjectives = 'happy sad lonely cold hot ugly pretty thin fat big small tall short'.split()
names = {'animals': animals, 'colors': colors, 'adjectives': adjectives}
categories = [names['animals'],names['colors'],names['adjectives']]

def getRandomWord(wordList):
    wordList = random.choice(list(names.keys())) 
    wordIndex = random.randint(0,len(wordList))
    print(animals[wordIndex])

    if(random.choice(list(names.keys())) == 'animals'):
        print("The category is animals!")
        return animals[wordIndex]
    if(random.choice(list(names.keys())) == 'colors'):
        print("The category is colors!")
        return colors[wordIndex]    
    if(random.choice(list(names.keys())) == 'adjectives'):
        print("The category is adjectives!")
        return adjectives[wordIndex]

問題を解決するにはどうすればよいですか?

4

1 に答える 1

3

現在、別のカテゴリを 3 回描いています。と初めて比較したとき'animals'。第二に'colors'; と 3 番目に'adjectives'

しかし、一度描い'colors'てからまた描いたらどうなるでしょうか? 3 つの「if」ブランチはいずれもトリガーしません。実行されるものがないので、最後に有効があります。'animals''colors'returnreturn None

または、あなたnamesが思っているものではない場合は、None値を描画している可能性があります.スタックトレース全体を表示していないので、エラーが発生する場所を推測しています.

(また、wordIndexが に設定されている可能性があります。len(wordList)これは、最後のインデックスが であるため、IndexError になりますlen(wordList)-1。さらに、wordIndexは必ずしもカテゴリに関連付けられたリストから取得されるとは限らないため、そこでもインデックス作成エラーが発生する可能性があります。)

コードを次のように単純化できると思います。

import random
animals = 'ape bear beaver cat donkey fox goat llama monkey python bunny tiger wolf'.split()
colors = 'yellow red blue green orange purple pink brown black white gold'.split()
adjectives = 'happy sad lonely cold hot ugly pretty thin fat big small tall short'.split()
names = {'animals': animals, 'colors': colors, 'adjectives': adjectives}

def getRandomWord(words_by_category):
    category = random.choice(list(words_by_category.keys()))
    print("the category is", category)
    wordlist = words_by_category[category]
    chosen_word = random.choice(wordlist)
    return chosen_word

その後、次のようになります。

>>> getRandomWord(names)
the category is colors
'blue'
>>> getRandomWord(names)
the category is adjectives
'happy'
>>> getRandomWord(names)
the category is colors
'green'
>>> getRandomWord(names)
the category is animals
'donkey'
于 2013-07-21T05:23:01.743 に答える