【问题标题】:How to do an if statement based on a randomized string in Python?如何在 Python 中基于随机字符串执行 if 语句?
【发布时间】:2013-01-25 18:40:35
【问题描述】:
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. 
----------

【问题讨论】:

  • 这与if 有什么关系?我不明白。
  • 您想要做的只是打印不同的消息还是还有更多?不同的消息可以由字典处理。
  • 它与 if 有关,因为如果结果是 A,则打印特定于 A 的消息。我尝试了字典,但它不适合我的目的。字典没有在第一行正下方输出第二行。有没有办法做到这一点?

标签: python variables if-statement random statements


【解决方案1】:

我会使用字典,并使用代码(“A”,“B”,“C”)作为字典键,并将“消息”放入字典值。

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()))

【讨论】:

  • 啊,看起来差不多。我会试试看它是否适合我。我是初学者,所以这很有帮助。
  • 传递 codes.keys() 是否适用于 python3.x。我的印象是random.choice 要求输入是list
  • @mgilson 我不这么认为。对于 python3.x,另一种选择可能是 random.choice(list(codes.keys()))
  • 它在 py3k 上确实中断了。它要求输入是一个“序列”——虽然它可能只使用带有整数的__getitem__...但是是的,你需要list(codes.keys()) 使它与py3k 兼容。我不会提到它,除非你的 print 语句也适用于 py3k 所以...
  • 好点re:打印声明。我有时会在脑海中混淆 python2 和 3!
【解决方案2】:

这将为您提供问题中示例的结果:

#! /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])

【讨论】:

  • “像猴子球一样臭”。卖了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
相关资源
最近更新 更多