1

有没有办法可以使用此线程中回答的列表理解来创建字典?

listA = [
    "apple_v001",
    "apple_v002",
    "banana_v001",
    "orange_v001",
]
keywords = ["apple", "banana", "orange"]
[[item for item in listA if kw in item] for kw in keywords]
# Result: [['apple_v001', 'apple_v002'], ['banana_v001'], ['orange_v001']] # 

我想要做的是使用关键字作为这个结果的关键来创建一个字典。所以

dictA["apple"] = ['apple_v001', 'apple_v002']

等等。我尝试执行 dict = {key, value for ...(iteration) } 但总是出现语法错误。我真的不知道如何开始,任何帮助不胜感激。

4

4 回答 4

2
{kw: [item for item in listA if kw in item] for kw in keywords}

但这似乎不是创建这样一个字典的特别有效的方法

例如,这不需要预先列出关键字并且相当有效

>>> from itertools import groupby
>>> {k:list(g) for k,g in groupby(sorted(listA), key=lambda x:x.partition('_')[0])}
{'orange': ['orange_v001'], 'apple': ['apple_v001', 'apple_v002'], 'banana': ['banana_v001']}

对于 Python2.6,等效的是

dict((kw, [item for item in listA if kw in item]) for kw in keywords)

>>> from itertools import groupby
>>> dict((k,list(g)) for k,g in groupby(sorted(listA), key=lambda x:x.partition('_')[0]))
{'orange': ['orange_v001'], 'apple': ['apple_v001', 'apple_v002'], 'banana': ['banana_v001']}
于 2013-03-05T04:00:09.893 回答
2

如果您不想使用一种衬垫解决方案,请检查此

In [58]: d
Out[58]: defaultdict(<type 'list'>, {})

In [59]: for elem in keywords:
   ....:     for item in listA:
   ....:         if item.startswith(elem):
   ....:             d[elem].append(item)
   ....:

In [60]: d
Out[60]: defaultdict(<type 'list'>, {'orange': ['orange_v001'], 'apple': ['apple_v001', 'apple_v002'], 'banana': ['banana_v001']})
于 2013-03-05T04:01:48.743 回答
1

在您提到您使用 Python 2.6 的评论中。Python 2.6 中没有 dict 理解,您可以使用dict()生成器表达式来代替:

d = dict((kw, [item for item in listA if kw in item]) for kw in keywords)

这是一个可能更有效的版本:

import re
from collections import defaultdict

search_word = re.compile("(%s)" % "|".join(map(re.escape, keywords))).search

d = defaultdict(list)
for item in listA:
    m = search_word(item)
    if m:
       d[m.group(1)].append(item)

如果listA始终采用问题中给出的格式:

from collections import defaultdict

keywords = set(keywords)
d = defaultdict(list)
for item in listA:
    word = item.partition("_")[0]
    if word in keywords:
       d[word].append(item)

如果listA不包含不在的项目keywords

from collections import defaultdict

d = defaultdict(list)
for item in listA:
    d[item.partition('_')[0]].append(item)
于 2013-03-05T04:34:08.960 回答
0

You can use a regex:

>>> import re
>>> listA = [
...     "apple_v001",
...     "apple_v002",
...     "banana_v001",
...     "orange_v001",
... ]
>>> keywords = ["apple", "banana", "orange"]
>>> s=' '.join(listA)
>>> dict([(e,re.findall(r'{}_v\d+'.format(e),s)) for e in keywords])
{'orange': ['orange_v001'], 'apple': ['apple_v001', 'apple_v002'], 'banana': ['banana_v001']}

Or (post Python 2.7) a dict comprehension:

>>> {e:re.findall(r'{}_v\d+'.format(e),s) for e in keywords}
{'orange': ['orange_v001'], 'apple': ['apple_v001', 'apple_v002'], 'banana': ['banana_v001']}
于 2013-03-05T05:04:58.260 回答