2015-05-15 33 views
-1

我必须在Python中实现下面的伪代码。Python for循环单线程连接2个字符串

dict = {} 
list1 = [1,2,3,4,5,6] 
list2 = [2,4,5,7,8] 
dict['msg'] = "List 2 items not in list 1 : " 

for x in list 2: 
    if x in list1: 
     dict['msg'] += x 

<write in log : dict['msg']> 

如果我使用味精的价值列表

dict['msg'] = ["List 2 items not in list 1 : "] 

我可以追加在单排的值作为

[dict['msg'].append(x) for x in L2 if x not in L1] 

但随后的输出页面上的结果将作为

msg : [ 
    "List 2 items not in list 1 :", 
     7, 
     8 
     ] 

我想要结果si斜线为

msg : List 2 items not in list 1 : 7,8 

我该如何做到这一点?

回答

1

不知道你为什么试图在这里首先使用字典。与字符串和列表相同。在打印时,我将列表转换为字符串。

list1 = [1,2,3,4,5,6] 
list2 = [2,4,5,7,8] 
msg = "List 2 items not in list 1 : " 
exclusion = [ str(i) for i in list2 if i not in list1 ] 
print msg, ', '.join(x) 

输出:

列表2项不在列表中的1:7,8


随着字典:

list1 = [1,2,3,4,5,6] 
list2 = [2,4,5,7,8] 
d['msg'] = "List 2 items not in list 1 : " 
d['msg'] = [ str(i) for i in list2 if i not in list1 ] 
print d['msg'] 

输出:

“列表2项不在列表中的1:7,8”

+0

因为我需要为其余代码的字典。 – pratibha

+0

已更新的回答。 –