0
codes = ["A", "B", "C", "D", "E"]
random.shuffle(codes)

    def print_message(message):
        print "\n"
        print "-"*10
        print message
        print "-"*10
        print "\n"

    print_message('This is a test of the %s system' % codes[0])

次に、提示されたランダムな文字に基づいて print_message('This... ') の結果に対して if ステートメントを実行するにはどうすればよいですか。

例。コード[0]の結果がprint_message()の「A」になった場合、これが画面に表示されます。

----------
This is a test of the A system. 
The A system is really great. 
---------

コマンドをさらに数回実行すると、次のように表示されます。

----------
This is a test of the C system.
The C system sucks. 
----------

----------
This is a test of the B system. 
The B system has improved greatly over the years. 
----------
4

2 に答える 2

3

辞書を使用し、コード (「A」、「B」、「C」) を辞書キーとして使用し、「メッセージ」を dict 値に入れます。

codes = {
    'A': 'The A system is really great.',
    'B': 'The B system has improved greatly over the years.',
    'C': 'The C system sucks.'
}

random_key = random.choice(codes.keys())
print("This is a test of the %s system" % random_key)
print(codes[random_key])

注: @mgilson が指摘したように、python 3.x のrandom.choice場合、リストが必要なため、代わりにこれを行うことができます。

random_key = random.choice(list(codes.keys()))
于 2013-01-25T18:47:29.063 に答える
1

これにより、質問の例の結果が得られます。

#! /usr/bin/env python
import random
codes = ["A", "B", "C", "D", "E"]
random.shuffle(codes)

def print_sys_result(sys_code):
    results = {
        "A": "is really great",
        "B": "has improved greatly over the years",
        "C": "sucks",
        "D": "screwed us up really badly",
        "E": "stinks like monkey balls"
    }
    print "\n"
    print "-"*10
    print 'This is a test of the {0} system'.format(sys_code)
    if sys_code in results:
        print "The {0} system {1}.".format(sys_code, results[sys_code])
    else:
        print "No results available for system " + sys_code
    print "-"*10
    print "\n"

print_sys_result(codes[0])
于 2013-01-25T19:01:40.970 に答える