将列表列表与字典进行比较,并将输出作为元组列表的列表

时间:2018-02-11 15:35:32

标签: python python-3.x list dictionary tuples

我有一个字符串列表和一个字典列表:

docsp = [['how', 'can', 'I', 'change', 'this', 'car'], ['I', 'can', 'delete', 'this', 'module']]

ent = {'change' : 'action', 'car' : 'item', 'delete' : 'action'}

我想将字典与列表列表进行比较,并将列表元素与字典键值对标记为新的元组列表,如下所示。

newlist = [[('how', 'O'), ('can', 'O'), ('I', 'O'), ('change', 'action'), ('this', 'O'), ('car', 'item')], [('I', 'O'), ('can', 'O'), ('delete', 'action'), ('this', 'O'), ('module', 'O')]]

我尝试了以下代码:

n = []
for k,v in ent.items():
    for i in docsp:
        for j in i:
            if j==k:
                n.append((j,v))
            n.append((j, 'O'))
n

并获得以下输出:

[('how', 'O'),
 ('can', 'O'),
 ('I', 'O'),
 ('change', 'action'),
 ('change', 'O'),
 ('this', 'O'),
 ('car', 'O'),
 ('I', 'O'),
 ('can', 'O'),
 ('delete', 'O'),
 ('this', 'O'),
 ('module', 'O'),
 ('how', 'O'),
 ('can', 'O'),
 ('I', 'O'),
 ('change', 'O'),
 ('this', 'O'),
 ('car', 'item'),
 ('car', 'O'),
 ('I', 'O'),
 ('can', 'O'),
 ('delete', 'O'),
 ('this', 'O'),
 ('module', 'O'),
 ('how', 'O'),
 ('can', 'O'),
 ('I', 'O'),
 ('change', 'O'),
 ('this', 'O'),
 ('car', 'O'),
 ('I', 'O'),
 ('can', 'O'),
 ('delete', 'action'),
 ('delete', 'O'),
 ('this', 'O'),
 ('module', 'O')]

我浏览了这个link,但无法修改它以获得我预期的输出。

1 个答案:

答案 0 :(得分:1)

这是一个利用列表理解的解决方案:

  array(1) {
    ["custom_data"]=>
    array(1) {
      ["MY_PAREMETER"]=>
      string(4) "wow!"
    }
  }