从目录中的列表创建JSON,由另一个列表

时间:2017-06-30 09:34:23

标签: python

我对Python很陌生,我发现自己需要从列表中创建JSON,对它们进行排序并将它们存储在另一个列表中创建的目录中。

我们说list1是:

- ABC
- DEF
- GHI
- ...

而list2是:

 - ABCabc
 - ABCdef
 - DEFabc 
 - GHIabc
 - GHIdef
 - ...

我已经成功地从list1创建了目录。 但是现在我需要一种方法来创建list2中的值,这些值的名称以list1的值开头,作为list1目录中的index.json。

所以我正在寻找的是:

 - ABC
    - index.json
 - DEF
    - index.json
 - GHI
    - index.json
 - ...

index.json的内容如下所示:

{
"foobar":[{
        "ABC":"ABCabc"
    },
    {
        "ABC":"ABCdef"
    }]
}

到目前为止我的JSON代码:

if [s for s in result if s.startswith(data_extr2)]:
    for i in result:
        try:
            with io.open(os.path.join("index.json"), 'w', encoding="utf-8") as output:
                output.write(unicode(json.dumps(result, ensure_ascii=False)))
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise

其中data_extr2为list1,result为list2。

提前干杯

1 个答案:

答案 0 :(得分:0)

我不太了解您的代码,对我而言,它已被破坏。

Input: A of size n, k
Output: d

sort(A)
adj_diff = array of n - 1 elements
for i = 0 ... n - 2
    adj_diff[i] = A[i + 1] - A[i]
sort(adj_diff)
d = adj_diff[n - 1 - k]
if d == adj_diff[n - 2 - k] // to make sure there are at most k groups,
    d++                     // otherwise we might have multiple groups
                            // with the same distance to their neighbors

这里有一个代码做你想要的,我希望它能帮助你理解,当然这个代码可以改进,但它是向你展示一个简单的解决方案。

# if statement on a list ? It will return True if the list is not empty
# bool([]) == False and bool([1]) == True
# If you want to check if the list is empty, you can use len(results) to return the length of the list.
if [s for s in result if s.startswith(data_extr2)]: 

# startswith take a string in argument, not a list, it should provoke an error
s.startswith(data_extr2)