将包含列表的元组列表转换为一个json数组

2024-09-27 00:13:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有元组列表,其中一些元组包含列表作为第一个元素。我需要将这个列表转换成json数组。在

我还阅读了StackOverflow的相关内容,例如herehere和{a3}等,但是没有一个直接解决这个问题。在

我尝试了以下方法,正如发现的here 在这种方法中,我所拥有的每个列表都是在遍历txt文件的每一行并对每行执行一个操作之后生成的。在

示例代码:

填充

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.

示例代码

^{pr2}$

提取项的结果

^{3}$
    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库还是使用另一种方法来实现我的理解列表?在


Tags: 方法jsonhome列表herelocationareyes
1条回答
网友
1楼 · 发布于 2024-09-27 00:13:20

下面的代码似乎有效。可能对您的整个数据集有效,这取决于您要做的事情(您需要多大的灵活性)。在

#!/usr/env python3

import json


a = [
    [
        ('dalmations', 'dog'),
        ('white', 'color'),
        ('yes', 'pet'),
        ('house', 'location'),
    ],
    [
        ('huskies', 'dog'),
        ('grey', 'color'),
        ('yes', 'pet'),
        ('house','location')
    ],
    [
        ('pitbulls', 'dog'),
        ('beige', 'color'),
        ('yes', 'pet'),
        ('house','location')
    ]
]

b = []
for row in a:
    data = {}
    for word in row:
        data[word[1]] = [word[0],]
    b.append(data)

print(json.dumps(b))

这样可以得到:

^{pr2}$

相关问题 更多 >

    热门问题