【问题标题】:Compare list of lists with a dictionary and get output as list of list of tuples将列表列表与字典进行比较,并将输出作为元组列表的列表
【发布时间】:2018-02-11 15:35:32
【问题描述】:

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

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 ,但无法修改它以获得我的预期输出。

【问题讨论】:

  • 你需要在if j==k之后添加一个else子句来追加(j, 'O'),而不是无条件追加。
  • 试过了。但我仍然得到与上面相同的输出。
  • 请说明您的具体尝试。

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


【解决方案1】:

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

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

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

result = [[(docsp[i][j], ent.get(docsp[i][j], 'O')) for j in range(len(docsp[i]))] \
                                                    for i in range(len(docsp))]

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

【讨论】:

  • 我使用您的方法得到以下输出: [[(('how', 'O'), 'O'), (('can', 'O'), 'O '), (('I', 'O'), 'O'), (('change', 'action'), 'O'), (('this', 'O'), 'O') , (('car', 'item'), 'O')], [(('I', 'O'), 'O'), (('can', 'O'), 'O') , (('delete', 'action'), 'O'), (('this', 'O'), 'O'), (('module', 'O'), 'O')]]
  • 它对我有用。我已经用你提供的输入更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多