1

ラズベリーパイで「list.count」関数を使用しようとすると、

   Name Error: name 'count' is not defined

私にできることはありますか?よろしくお願いします。私はPythonを使用しています。私はPythonを使い始めたばかりで、私のチュートリアルではそれが述べています

   >>>count(seq,'a')

「seq」は、先ほど入力した一連の文字です。シーケンス内の「a」の数をカウントするためのものだと思います.453

迅速な対応と回答をありがとうございました。問題は解決しました。これは私が初めてオンラインで質問したものです。Markus Unterwaditzer による 2 番目の回答は、最終的に 'seq.count('a')' で問題を解決しました

また、チュートリアルを見つけて、問題が発生した理由を説明してくれた DSM にも感謝します。今ではすべてが機能しており、最初のコンピューター言語の学習に戻っています。

4

3 に答える 3

4

ああ。チュートリアルの魔法は

from string import *

これは悪い習慣です。function を含む string モジュールのすべてをスコープにインポートしますstring.count

>>> print string.count.__doc__
count(s, sub[, start[,end]]) -> int

    Return the number of occurrences of substring sub in string
    s[start:end].  Optional arguments start and end are
    interpreted as in slice notation.

countも文字列のメソッドなので、次のように書くことができます

>>> 'aaa'.count('a')
3

これは一般的に好まれます。現代の Python では、モジュールには関数さえありstringません。count

于 2013-02-06T20:14:37.913 に答える
1

I expect it is meant to count the number of 'a's in the sequence

内容によってlistは、おそらく正しい構文ではありません。が文字列の場合list、これを行うことができます:

>>>a = "hello"
>>>a.count('h')
1
>>>a.count('l')
2

「リスト」でも同じように機能します。

>>>a = ['h','e','l','l','o']
>>>a.count('l')
2
于 2013-02-06T19:57:47.853 に答える
1
>>> seq = ['a', 'b', 'c', 'a']
>>> seq.count('a')
2
>>> type(seq) is list  # the reason it's mentioned as list.count
True
>>> list.count(seq, 'a')  # the same thing, but nobody does it like that
2
于 2013-02-06T19:57:54.543 に答える