For example, how would I optimally merge:
res_str = ['[1,2,3]','[4,5,6]','[7,8,9]','[10,11,12]']
for example: ['[{'a': u'中国', 'b': u'美国', 'c': u'日本', 'd': u'德国', 'e': u'法国'},]','[{'a': u'中国', 'b': u'美国', 'c': u'日本', 'd': u'德国', 'e': u'法国'},]',]
into:
[1,2,3,4,5,6,7,8,9,10,11,12]
I used the following code, but is is not fast enough:
[x for j in res_str for x in eval(j)] spend time 0.65s
list(itertools.chain.from_iterable([eval(i) for i in res_str])) spend time 0.57s
Is there a better way to write this?
apart from a generator
(x for j in res_str for x in eval(j))
other way
sum([eval(i) for i in res_str],[]) spend time 3.87s
this way:
import ast
import itertools
l = ['[1,2,3]','[4,5,6]','[7,8,9]','[10,11,12]']
l = list(itertools.chain(*map(ast.literal_eval, l)))
spend time 0.95s
if use eval
list(itertools.chain(*map(eval, res_str)))
spend time 0.58s
this way:
eval('+'.join('+'.join(arr))) spend time 3.5s
this way:
import ast
import numpy as np
res_str = ['[1,2,3]','[4,5,6]','[7,8,9]','[10,11,12]']
print(list(np.array([ast.literal_eval(i) for i in res_str]).flatten()))
spend time 1s
if use eval list(np.array([eval(i) for i in res_str]).flatten()) spend time 0.58s