2013-12-07 153 views
0

我无法找到正确的输出。让我们说,我给出了两个列表,列表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'] 
+2

如何使用“” .joiin(A) ? – Jae

回答

3

在Python 2.x中:

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

在Python 3.X:

print('Solution A:', *A) 

注意的是Python 3.x中print功能上,它的提供的对象会自动调用str。由此' '.join需要的对象已经是字符串,所以要确保使用的:

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

或者:

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

@alko可能 - 请参阅我对iCodez的评论 –

2

您可以使用str.joinstr.format

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

这里是map参考。

+0

我想知道他们是否需要对它们进行strify处理......当前输出和示例输入在类型 –

+0

之间似乎相互矛盾谢谢@iCodez for代码。我从未使用{}和格式。但是用于将对象放置在{}内的格式? – user2933041

+0

@ user2933041 - 是的,这正是发生了什么事情。例如,'“{} {} {}”。格式(1,2,3)'将产生'“123”'。 – iCodez

0

使用连接函数将您的列表转换为字符串,然后格式化它们。

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

您可以设置一个小功能的物品格式为文本字符串,你会避免重复,当你格式化:

def textlist(mylist): 
    return ' '.join(map(str, mylist)) 

print "Solution A: {0} \nSolution B: {1}".format(textlist(A), textlist(B)) 
+0

注意:在Python 2.7+中,您可以省略大括号内的数字。 – iCodez