Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.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中简化此代码?_Python - Fatal编程技术网

如何在python中简化此代码?

如何在python中简化此代码?,python,Python,任务是将100以下的所有3的倍数相加 num1 = 0 l = [] while num1 < 100: num1 = num1 + 3 l.append(num1) # I used this to delete the last element in the list which is 102, del l[-1] print l # sum of all the numbers in l b = sum(l) print b num1=0 l=[] 当num1

任务是将100以下的所有3的倍数相加

num1 = 0
l = []
while num1 < 100:
    num1 = num1 + 3
    l.append(num1)
# I used this to delete the last element in the list which is 102,
del l[-1]
print l
# sum of all the numbers in l
b = sum(l)
print b
num1=0
l=[]
当num1<100时:
num1=num1+3
l、 追加(num1)
#我用它来删除列表中的最后一个元素102,
德尔l[-1]
打印l
#l中所有数字的总和
b=总和(l)
打印b
备选方案,一个班轮:

answer = sum(range(0, 100, 3))
您可以尝试以下方法:

sum(range(0, 100, 3))
通过高斯和

total = 3 * (100 // 3) * (100 // 3 + 1) // 2

好的,所以
sum(范围(31000,3))
毕竟不是最酷的。哦,你已经赢了我几秒钟了。。。这就是当您的Internet连接速度较慢时会发生的情况:D的范围不应该从3开始?与中一样,
范围(3100,3)
?该列表包含0,0不是3的倍数。当然,总和是正确的,但这是原理……有趣的是,我一直认为0是3的倍数,因为0%3是0取决于你想要使用的定义。一般来说(回想我的大学生活),人们只关注正整数倍数。实际上,结果是一样的,但在这种情况下,从0开始的范围是多余的。@Jesus:这是一个有效的问题。我认为它得到了反对票(不是我),因为这是一个“我如何使我的代码更好?”的问题,通常属于codereview.stackexchange.com我的问题如何不够清楚?我已经收到了几个用户的答案,这是我一直在寻找的答案。
total = 3 * (100 // 3) * (100 // 3 + 1) // 2