【问题标题】:find matching values in list of dictionaries and pair the strings在字典列表中查找匹配值并将字符串配对
【发布时间】:2019-06-06 14:50:48
【问题描述】:

我无法想出一个可以满足我要求的代码片段。

我有一个使用这种结构的字典列表:

word = {'word': 'Dog', 'loc': 160}

它们被附加到 for 循环中的列表中:

words = []

for line in lines:
  word = {'word': line['WordText'], 'loc': line['Location']}
  ...
  words.append(word)

每一行都有一个location 整数,我需要稍后将文本与该行配对。

我需要在列表中找到键 loc 的值匹配的所有实例,然后以某种方式将它们配对。

(Python)伪代码:

new_lines = []

for word in words:
  new_line = {'line': '', 'loc': 0}
  if a_word['loc'] == another_word['loc']:
    new_line['line'] = a_word['word'] + another_word['word']
    new_line['loc'] = a_word['loc']
    new_lines.append(new_line)

我知道这不是正确的方法,但我需要某种 if any word['loc'] matches any other word['loc']: then put into list 之类的东西。

如果不清楚,我想将字典中 loc 值匹配的 单词 配对。

【问题讨论】:

  • 你的目标是什么?您是否试图找到有一些共同词的成对线?或者您是否打算查找包含某个单词的所有行?前者可能会产生过多的组合。后者会容易得多
  • @AlainT。请查看我的编辑

标签: python list dictionary for-loop


【解决方案1】:

您可以构建一个字典,其中每个位置都收集一个单词列表。然后过滤掉只有一个词的位置。

from collections import defaultdict

lines = [{'WordText': 'dog',   'Location': 11},
         {'WordText': 'cow',   'Location': 222},
         {'WordText': 'cat',   'Location': 11},
         {'WordText': 'horse', 'Location': 222},
         {'WordText': 'duck',  'Location': 55},
         {'WordText': 'goat',  'Location': 222}]

wordsAtLoc = defaultdict(set)
for line in lines:
    wordsAtLoc[line['Location']].add(line['WordText'])
matches = { loc:list(words) for loc,words in wordsAtLoc.items() if len(words)>1 }   

print(matches)
# {11: ['cat', 'dog'], 222: ['goat', 'horse', 'cow']}

【讨论】:

  • 很棒,即使一个位置有多个单词,它也能正常工作。
【解决方案2】:

我需要在列表中找到键 loc 的值匹配的所有实例,然后以某种方式将它们配对。

使用默认字典按'loc'对单词进行分组。

有了这个,你可以遍历 'd' 并做你喜欢做的事情。

from collections import defaultdict

d = defaultdict(list)

words = [{'word': 'fog', 'loc': 12}, {'word': 'bird', 'loc': 122}, {'word': 'bag', 'loc': 12},
         {'word': 'main', 'loc': 33}]

for word in words:
    d[word['loc']].append(word['word'])
print(d)

输出

defaultdict(<class 'list'>, {12: ['fog', 'bag'], 122: ['bird'], 33: ['main']})

【讨论】:

    猜你喜欢
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多