使用while循环检查单独的变量

时间:2018-09-26 12:45:59

标签: python python-3.x

我正在尝试使用具有相似名称的独立变量来检查4个独立变量是否具有完全相同的字符串。下面是一个示例。打印功能也是一个例子,它们不是我的最终目标。

from random import randint
example1 = randint(1,3)
example2 = randint(1,3)
example3 = randint(1,3)
example4 = randint(1,3)
if example1 == 1:
  print ("A")
elif example1 == 2:
  print ("C")
else:
  print ("M")

有人能建议我如何对所有变量重复该区域吗?

if example1 == 1:
  print ("A")
elif example1 == 2:
  print ("C")
else:
  print ("M")

3 个答案:

答案 0 :(得分:2)

str删除randint(str(1,3))

l = [example1, example2, example2, example4]

for i in l:
    if i == 1:
      print ("A")
    elif i == 2:
      print ("C")
    else:
      print ("M")

[print('A') if i == 1 else print('C') if i ==2 else print('M') for i in l]
C
C
C
A

答案 1 :(得分:0)

您可以使用for循环:

from random import randint
example1 = randint(1,3)
example2 = randint(1,3)
example3 = randint(1,3)
example4 = randint(1,3)
for example in (example1, example2, example3, example4):
  if example == 1:
    print ("A")
  elif example == 2:
    print ("C")
  else:
    print ("M")

(example1, example2, example3, example4)部分创建一个包含所有四个变量的tuple。然后for example in ...部分为每个变量重复您想要的代码,而example变量每次在循环中都采用每个不同变量的值。

有关for循环的更多信息,您可以查看official tutorial

答案 2 :(得分:0)

一种更具扩展性的方法来解决您的问题:

from random import randint
example1 = randint(1,3)
example2 = randint(1,3)
example3 = randint(1,3)
example4 = randint(1,3)

int_char_map = {1: "A", 2: "C", 3: "M"}

examples = [example1, example2, example2, example4]

print(examples)

for example in examples:
    print(int_char_map[example])