正如@alecxe所指出的,您需要将从文件中获得的列表数组划分为包含7个或更少元素的值组。然后,您可以获取一个包含任意7个标题的列表,并将它们用作键来创建最终列表中每个json对象的字典。try:
from itertools import izip
except ImportError: # Python 3
izip = zip
try:
xrange
except NameError: # Python 3
xrange = range
def grouper(n, sequence):
for i in xrange(0, len(sequence), n):
yield sequence[i:i+n]
data = [['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
['String 6'],['String 7'],['String 8'],['String 9'],['String 9'],
['String 10']]
titles = ['title1', 'title2', 'title3', 'title4', 'title5', 'title6', 'title7']
values = [e[0] for g in grouper(7, data) for e in g]
keys = (titles[i%7] for i in xrange(len(values)))
objs = [dict(g) for g in grouper(7, list(izip(keys, values)))]
print(objs)
输出:[{'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 9', 'title4': 'String 10'}]