1

私に与えられた課題のためのプログラムを作成しています: 文字列を取得し、その文字のそれぞれの ascii 値を見つけ、それらの数字を足し合わせて最終的な値を返します。私はここまで来ました:

def AddAsciiList(string):
    ascii = [ord(c) for c in string]
    for item in ascii:
        print item
        total = ascii[i-1] + ascii[i]
    return total
string = raw_input("Enter String:")
AddAsciiList(string)

「印刷項目」ステートメントは、何が問題なのかを理解するのに役立ちました。total = ステートメントがまだ機能しないことはわかっています。修正に取り掛かります。基本的に私が求めているのは、なぜ「印刷項目」は数字 97 を印刷するのですか?!

4

2 に答える 2

4

これは、ord()が数値の ASCII コードを返し、asciiリストにコードが含まれているためです。例を参照してください -

>>> testString = "test"
>>> testList = [ord(elem) for elem in testString]  # testList = map(ord, testString) is another way.
>>> testList
[116, 101, 115, 116]

そして、リストを反復処理すると、出力される整数値が得られます。

次のように、入力文字列に が含まれ97ている必要があるため、出力されます。'a'

>>> chr(97)
'a'

関数の意味を確認してくださいhelp-

>>> help(ord)
Help on built-in function ord in module __builtin__:

ord(...)
    ord(c) -> integer

    Return the integer ordinal of a one-character string.

文字列内の文字のすべての ASCII コードを合計したい場合は、次のようにします。

>>> sum(map(ord, testString))
448

また

>>> sum(ord(elem) for elem in testString)
448
于 2013-07-16T19:41:56.120 に答える
0

In your second statement, you're creating a list of integers. Let's look at an example:

>>> s = 'abcde'
>>> a = [ord(c) for c in s]
>>> a
[97, 98, 99, 100, 101]
>>> 

If you want to sum the items in the list, just use sum.

>>> sum(a)
495

If you want to do the whole thing in one swell foop:

>>> total = sum(ord(c) for c in s)
>>> total
495

Hope this helps.

于 2013-07-16T19:59:34.867 に答える