Python for loop单线程用于连接2个字符串

时间:2015-05-15 08:39:22

标签: python-2.7

我必须在python中实现下面的伪代码。

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

如果我使用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
      ]

我希望结果为单行

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

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

不知道你为什么要在这里尝试使用dict。与字符串和列表相同。打印时我将列表转换为字符串。

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)

输出:

  

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

用dict:

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'