我希望我的输出是:
Enter a number : n
List from zero to your number is : [0,1,2,3, ... , n]
0 + 1 + 2 + 3 + 4 + 5 ... + n = sum(list)
但我的实际产出是:
^{pr2}$我使用join
,因为它是我唯一知道的类型。在
为什么在项目周围印上加号,为什么它们在空白处周围?在
我应该如何将list
的值打印成字符串供用户阅读?在
谢谢。我的代码是:
##Begin n_nx1 application
n_put = int(input("Choose a number : "))
n_nx1lst = list()
def n_nx1fct():
for i in range(0,n_put+1):
n_nx1lst.append(i)
return n_nx1lst
print ("List is : ", n_nx1fct())
print ('+'.join(str(n_nx1lst)) + " = ", sum(n_nx1lst))
将
list
中的每个int
元素改为.join
调用内的str
,方法是使用generator expression
:在第一种情况下,您对整个}中的单个元素进行调用。因此,它将连接列表表示中的每个字符,如下所示:
^{pr2}$list
调用str
,而不是对该{使用
+
符号生成您所看到的结果。在您需要做的是将一个字符串元素与列表中每个元素的“+”连接起来。你所需要的就是有一些字符串格式。在
样本输出:
^{pr2}$它是如何工作的?
我们使用所谓的list comprehension (5.1.3)(生成器在这个特定用法中)迭代我们的
int
元素列表,创建string
元素的list
。现在我们可以使用string
方法join()
来创建我们想要的格式。在您不需要调用列表中的
str
。返回列表的str表示形式,其输出用'+'
联接。在您可以使用^{} 将列表中的每个项目转换为
str
,然后join
:您也可以使用新样式格式来获得更具可读性的输出:
^{pr2}$相关问题 更多 >
编程相关推荐