改版印刷品

2024-10-02 14:26:42 发布

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

我找不到正确的输出。假设我有两张单子,单子A和单子B

list A = [1,2,3]
list B = [2,3,4]

我想打印一份如下的声明。。你知道吗

Solution A : 1 2 3
Solution B : 2 3 4

到目前为止我所做的是。。。你知道吗

    A = config.mList
    B = config.sList
    return 'Solution A: %s \nSolution B: %s' %(A, B) 

这只是打印出来的

Solution A: ['17', '4', '8', '11'] 
Solution B: ['9', '18', '13']

Tags: config声明returnlist单子solutionslistmlist
3条回答

使用join函数将列表转换为字符串,然后格式化它们。你知道吗

' '.join(A) #  "1 2 3"

在Python 2.x中:

print 'Solution A:', ' '.join(A)

在Python 3.x中:

print('Solution A:', *A)

请注意,python3.x中的print函数会自动调用它提供的对象上的str。其中' '.join要求对象已经是字符串,因此要确保使用:

print ' '.join([str(el) for el in A])

或:

print ' '.join(map(str, A))

可以使用^{}^{}

>>> A = ['1','2','3']
>>> B = ['2','3','4']
>>> print "Solution A : {}\nSolution B : {}".format(" ".join(A), " ".join(B))
Solution A : 1 2 3
Solution B : 2 3 4
>>>

但是请注意,在使用str.join之前,列表中的项必须是字符串。在示例中,您给出了整数列表。所以,如果你有这些,你可以这样做:

>>> A = [1,2,3]
>>> B = [2,3,4]
>>> print "Solution A : {}\nSolution B : {}".format(" ".join(map(str, A)), " ".join(map(str, B)))
Solution A : 1 2 3
Solution B : 2 3 4
>>>

这里有一个关于^{}的参考。你知道吗

相关问题 更多 >