我有一个以前输出到文本文件的字典,即[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
,by 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')
foo foo
,我的python字典将返回['Foo bar language','computing']
,我应该如何读取文本文件?
作为对示例的回应,您可以使用列表理解来获得技术上更紧凑的代码。我不认为它们在这里增加了太多(尽管如果我们对它们进行分析,它们对于大型数据集可能更有效)。你知道吗
它们确实使代码更难阅读,所以在大多数情况下我真的不喜欢这种方法。你知道吗
如果您觉得您的解决方案是串联在一起的,并且您可以控制持久性代码,请以标准格式存储数据。你知道吗
相关问题 更多 >
编程相关推荐