该列表应该得到每个数字的平方。我设法做到了,但我需要删除序列中的最后一个逗号。
当我使用此代码时:
def multiplicator():
for a in range(3, 20):
b = (a*a)
print(b, end=",")
multiplicator()
我明白了:
9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361,
答案 0 :(得分:6)
您可以使用str.join
在字符串之间添加分隔符,这样可以处理不添加额外字符串的分隔符。
>>> ','.join(str(a*a) for a in range(3, 20))
'9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361'
答案 1 :(得分:1)
def multiplicator():
print_list = list()
for a in range(3, 20):
b = (a*a)
print_list.append(b)
print_list.append(',')
for i in print_list[:-1] :
print(i, end='')
multiplicator()
输出:
9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361
答案 2 :(得分:0)
一个简单的选择是:
def multiplicator():
for a in range(3, 19):
print(a*a, end=',') # directly a*a, no need for an intermediate variable
print(19*19)
通用解决方案是:
def multiplicator(n):
for a in range(3, n-1):
print(a*a, end=',')
print((n-1)*(n-1))
<强>输出:强>
>>> multiplicator(20)
9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361
注意:强>
这是一种简单而类似的方法,但你绝对应该使用@CoryKramer's来回答str.join()
答案 3 :(得分:0)
def funcPattern(n):
# Base case (When n becomes 0 or negative)
if (n == 0 or n < 0):
print(n, end=", ")
return
print(n, end=", ")
# First print decreasing order
funcPattern(n - k)
if (n == m):
print(n, end=" ")
elif (n != m):
print(n, end=", ")
n = 10
m = n
k = 2
funcPattern(n)
答案 4 :(得分:0)
一种方法:
a = range(3, 20)
print(*[i**2 for i in a], sep=',')
使用列表理解来创建列表,然后打印解压后的列表(使用*运算符);以','为分隔符。
输出将是:
9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361
答案 5 :(得分:-1)
您可以保留循环并添加条件:
def multiplicator():
for a in range(3, 20):
b = (a*a)
print(b, end="")
if a<19: # if not the last element
print(end=",") # print ","
print() # print new line after everything
multiplicator() # => 9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361
您还可以使用三元条件来缩短代码:
def multiplicator():
for a in range(3, 20):
b = (a*a)
print(b, end="," if a<19 else "")
print() # print new line after everything
multiplicator() # => 9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361