【发布时间】:2018-06-15 11:21:50
【问题描述】:
我有元组列表,其中一些元组包含列表作为第一个元素。我需要将此列表转换为 json 数组。
我也在 StackOverflow 上阅读过有关此问题的信息,例如 here、here 和 here 以及许多其他人,但没有一个直接解决该问题。
我尝试了以下方法,发现here 在这种方法中,我拥有的每个列表都是在遍历 txt 文件的每一行并对每一行执行操作后生成的。
示例代码:
infile:
Dalmations are white and yes they are pets who live at home.
Huskies tend to be grey and can be pets who also live at home.
Pitbulls usually are beige and can be pets who sometimes live at home.
示例代码:
inFile = '/data/sample.txt'
f = open(inFile, 'r').readlines()
def Convert(tup, di):
for a, b in tup:
di.setdefault(a[0]).append(b)
return di
dictionary = {}
for line in f:
keyTerms = extractTerms(line)
print keyTerms
extractTerms 的结果
[(u'dalmations', u'dog'), (u'white', u'color'), (u'yes', u'pet'), (u'house', u'location')]
[(u'huskies', u'dog'), (u'grey', u'color'), (u'yes', u'pet'),(u'house',u'location')]
[(u'pitbulls', u'dog'), (u'beige', u'color'), (u'yes', u'pet'),(u'house',u'location')]
allTerms = [(expandAllKeyTerms(a), b) for (a,b) in keyTerms]
print allTerms
[([u'dalmations', u'dalmation', u'dalmashun', u'dalmationz'], u'dog'), ([u'white'], u'color'), ([u'yes'], u'pet'), ([u'home'], u'location')]
[([u'huskies', u'husky', u'huskies'], u'dog'), ([u'grey'], u'color'), ([u'yes'], u'pet'), ([u'home'], u'location')]
[([u'pitbulls'], u'dog'), ([u'beige'], u'color'), ([u'yes'], u'pet'), ([u'home'], u'location')]
new = (Convert(allTerms, dictionary))
print new
样本(错误)最终输出:
{u'dog': [u'dalmations', u'huskies', u'pitbulls'], u'color': [u'white', u'grey', u'beige'], u'pet': [u'yes', u'yes', u'yes'], u'location': [u'home', u'home', u'home']}
我也尝试过使用import json // json.dumps(dictionary),但是,它还将所有值与一个对应的键相关联,而不是将每一行单独维护为自己的条目。
我的目标是达到以下格式
[{u'dog': [u'dalmations'], u'color': [u'white'], u'pet': [u'yes'], u'location': [u'home']};
{u'dog': [u'huskies'], u'color': [u'grey'], u'pet': [u'yes'], u'location': [u'home']};
{u'dog': [ u'pitbulls'], u'color': [u'beige'], u'pet': [u'yes'], u'location': [u'home']}]
有没有办法使用 json 库或其他列表理解来达到我想要的输出?
【问题讨论】:
-
显示
extractTerms和expandAllKeyTerms的来源 -
@GarbageCollector 来源是外部函数和长代码。我提供了每个单独函数的输出,但如果这有助于更多地情境化
-
一个字典不能有多个具有相同键的条目 - 这就是你想要做的吗?在这种情况下,您的列表列表(或元组列表)可以正常工作。
标签: python arrays json list tuples