0

我有一个以前输出到文本文件中的字典,即 [in]:

dict_from_file = """foo\tfoobar, bar, foo foo\tFoo bar language, computing\nprog\t python, java, c, c++\t computing\nedibles\tcereal, milka, whatever\tfood"""

最初,键是第 1 列,别名在第 2 列,第 3 列是值,我需要转换文本文件,使最后一列是键,第 1 列和第 2 列是值:

[出去]:

Foo bar language\tfoobar, foo, bar, foo foo
computing\tfoobar, foo, bar, foo foo, python, java, c, c++, prog
food\tcereal, milka, whatever\tedibles

这样做的目的是让给定输入foo foo,按getkeybyvalue()函数将返回['Foo bar language','computing']

我一直在东它如下:

from collections import defaultdict

outdict = defaultdict(list)
def getkeybyvalue(dictionary, value):
  return [i for i,j in dictionary.items() if value in j]

dict_from_file = """foo\tfoobar, bar, foo foo\tFoo bar language, computing\nprog\t python, java, c, c++\t computing\nedibles\tcereal, milka, whatever\tfood"""

for line in dict_from_file.split('\n'):
    column1, column2, column3 = line.strip().split('\t')
    #print column1, column2, column3
    for c3 in column3.split(','):
        c3 = c3.strip(', ')
        outdict[c3].append(column1)
        for c2 in column2.split(','):
            outdict[c3].append(c2.strip(' ,'))

for k in outdict:
    print k, outdict[k]

print getkeybyvalue(outdict, 'foo foo')
  1. 有没有更简洁的方法来做到这一点?
  2. 我还应该如何阅读给定的文本文件foo foo,我的 python 字典返回['Foo bar language','computing']
4

1 回答 1

1

作为对示例的回应,您可以使用列表推导来获得技术上更紧凑的代码。我不认为它们在这里增加了太多(尽管如果我们要对它们进行分析,它们对于大型数据集可能更有效)。

它们确实使代码更难阅读,所以在大多数情况下,我真的不喜欢这种方法。

如果您觉得您的解决方案串在一起并且您可以控制持久性代码,请以标准格式存储数据。

from collections import defaultdict

outdict = defaultdict(list)
def getkeybyvalue(dictionary, value):
    return [i for i,j in dictionary.items() if value in j]

dict_from_file = """foo\tfoobar, bar, foo foo\tFoo bar language, computing\nprog\t python, java, c, c++\t computing\nedibles\tcereal, milk, whatever\tfood"""

columns = [line.strip().split('\t') for line in dict_from_file.split('\n')]
for c1, c2, c3 in columns:
    for c3_item in c3.split(','):
        outdict[c3_item.strip(', ')] += [c1] + [c.strip(' ,') for c in c2.split(',')]

for k in outdict:
    print(k, outdict[k])

print(getkeybyvalue(outdict, 'foo foo'))
于 2013-12-07T19:39:30.287 回答