2015-05-15 36 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

已更新的回答。 –