在字符串中使用“+”符号联接列表项

2024-10-01 02:39:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望我的输出是:

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))

Tags: tofromnumberyourputislistsum
3条回答

list中的每个int元素改为.join调用内的str,方法是使用generator expression

print("+".join(str(i) for i in n_nx1lst) + " = ", sum(n_nx1lst))    

在第一种情况下,您对整个list调用str,而不是对该{}中的单个元素进行调用。因此,它将连接列表表示中的每个字符,如下所示:

^{pr2}$

使用+符号生成您所看到的结果。在

您需要做的是将一个字符串元素与列表中每个元素的“+”连接起来。你所需要的就是有一些字符串格式。在

def sum_of_input():
    n = int(raw_input("Enter a number : "))  # Get our raw_input -> int
    l = range(n + 1)  # Create our list of range [ x≥0 | x≤10 ]
    print("List from zero to your number: {}".format(l))
    print(' + '.join(str(i) for i in l) + ' = {}'.format(sum(l)))

样本输出:

^{pr2}$

它是如何工作的?
我们使用所谓的list comprehension (5.1.3)生成器在这个特定用法中)迭代我们的int元素列表,创建string元素的list现在我们可以使用string方法join()来创建我们想要的格式。在

>>> [str(i) for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
>>> ' + '.join(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
'1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10'

您不需要调用列表中的str。返回列表的str表示形式,其输出用'+'联接。在

您可以使用^{}将列表中的每个项目转换为str,然后join

print('+'.join(map(str, n_nx1lst)) + " = ", sum(n_nx1lst))

您也可以使用新样式格式来获得更具可读性的输出:

^{pr2}$

相关问题 更多 >