Convert a list to json objects

后端 未结 4 1665
我寻月下人不归
我寻月下人不归 2020-12-17 03:46

I have a huge text file.

line 1
line 2
line 3
...

I have converted it into an array of lists:

[[\'String 1\'],[\'String 2\'         


        
4条回答
  •  没有蜡笔的小新
    2020-12-17 04:22

    To solve this, you need to split the input list into chunks, by 7 in your case. For this, let's use this approach. Then, use a list comprehension producing a list of dictionaries:

    >>> from pprint import pprint
    >>> l = [['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
    ... ['String 6'],['String 7'],['String 8'],['String 9'],['String 10'],
    ... ['String 11']]
    >>> def chunks(l, n):
    ...     """Yield successive n-sized chunks from l."""
    ...     for i in range(0, len(l), n):
    ...         yield l[i:i+n]
    ... 
    >>>
    >>> result = [{"title%d" % (i+1): chunk[i][0] for i in range(len(chunk))} 
                  for chunk in chunks(l, 7)]
    >>> pprint(result)
    [{'title1': 'String 1',
      'title2': 'String 2',
      'title3': 'String 3',
      'title4': 'String 4',
      'title5': 'String 5',
      'title6': 'String 6',
      'title7': 'String 7'},
     {'title1': 'String 8',
      'title2': 'String 9',
      'title3': 'String 10',
      'title4': 'String 11'}]
    

提交回复
热议问题