Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何压缩a';对于范围内的x';在';如果'';elif';在';而';陈述_Python_Python 3.x - Fatal编程技术网

Python 如何压缩a';对于范围内的x';在';如果'';elif';在';而';陈述

Python 如何压缩a';对于范围内的x';在';如果'';elif';在';而';陈述,python,python-3.x,Python,Python 3.x,我有一个生成数学表的代码,我觉得有可能被减少,因为我重复了三个相同的代码,但每个if/elif语句的解决方案都略有不同 num=10 x=str(input("Enter Math Operation (+, -, *): ")) while (x != "+" and x != "-" and x != "*"): x=str(input("\tEnter Math Operation: ")) if x=="+": for table in range(1,1

我有一个生成数学表的代码,我觉得有可能被减少,因为我重复了三个相同的代码,但每个if/elif语句的解决方案都略有不同

num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
    x=str(input("\tEnter Math Operation: "))
    if x=="+":
        for table in range(1,11):
            print(str(num),str(x),table,"=",num+table) 
    elif x=="-":
       for table in range(1,11):
            print(str(num),str(x),table,"=",num-table) 
    elif x=="*":
       for table in range(1,11):
            print(str(num),str(x),table,"=",num*table)

请告诉我如何压缩此代码。

您可以使用查找表存储不同的函数

num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
    x=str(input("\tEnter Math Operation: "))
ops = {
    '+': lambda x, y: x+y,
    '-': lambda x, y: x-y,
    '*': lambda x, y: x*y}

fn = ops[x]
for table in range(1,11):
    print(str(num),str(x),table,"=",fn(num,table))

函数是python中的第一类对象。将正确的函数赋给变量,然后使用它

num=10
x=str(input("Enter Math Operation (+, -, *): "))
# Read operation
while (x != "+" and x != "-" and x != "*"):
    x=str(input("\tEnter Math Operation: "))
# Select appropriate function
if x=="+":
    op = lambda x, y : x + y
elif x=="-":
    op = lambda x, y : x - y
elif x=="*":
    op = lambda x, y : x * y

# Use function
for table in range(1,11):
    val = op(num, table)
    print(str(num), str(x),table,"=", val)

您通常会这样做:

  • 将运算符作为函数存储在变量中

  • 使用字典查找运算符

  • 使用
    .format()
    而不是将许多字符串放在一起

  • 如果参数已经是字符串,则不要使用
    str()

下面是它的样子:

import operator
x = 10
operators = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
}
while True:
    op_name = input('Enter Math Operation ({}): '.format(', '.join(operators)))
    op_func = operators.get(op_name)
    if op_func is not None:
        break
for y in range(1, 11):
    print('{} {} {} = {}'.format(x, op_name, y, op_func(x, y)))

您可以为包含if的循环创建一个,但对于大型表来说,这会更慢。您可以将exec与正确的运算符一起用作字符串,但它速度慢且易受攻击。您可以将一个add、subtract等函数传递给迭代列表的循环,但这样做会过多且速度较慢。简而言之,我认为这里的代码复制量是可以接受的。干,但不太干……他可以,但在这个简单的案例中,你会这么做吗?@JacquesDeooge我可能不会,但我希望一个代码审查者会告诉我,我已经重复了两行代码三次——这足以让我感到干。如果他们这样做了,我当然会解决。这是一个比我更好的答案——桌子比elif链要优雅得多。@JacquesChooge 1。最昂贵的是“印刷品”。2.性能不是问题,除非度量告诉您它是问题(清晰性比过早优化更重要。3.如果性能确实是一个问题,python可能是这方面的错误语言。我不认为这些列表可能包含一百万项……我同意清晰性比过早优化更重要。我认为在这方面使用表是不对的琐碎的例子不利于澄清。顺便说一句,如果运算符的数量会增加,我会选择表解决方案。;(天哪,这比以前的一些答案(我是其中一个答案的作者)好得多!这是了解python的人和真正的专家之间的区别。