我需要为list
的{{1}}生成scipy.optimize.minimize
,它应该如下所示:
boundry condition
我想知道是否有任何优雅的方式吗?
我试过了:
bonds = [(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99),
(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99),
(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99),]
但这会产生
bonds = [[(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99)] for i in range(3)]
如何将内部[[(0.0, 0.99), (-30, 30), (-30, 30), (0.0, 30), (0.0, 30), (-0.99, 0.99)],
[(0.0, 0.99), (-30, 30), (-30, 30), (0.0, 30), (0.0, 30), (-0.99, 0.99)],
[(0.0, 0.99), (-30, 30), (-30, 30), (0.0, 30), (0.0, 30), (-0.99, 0.99)]]
,[]
内部数组删除为一个?或者还有其他好办法吗?
答案 0 :(得分:10)
你可以这样做:
bonds = [(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99)] * 3
答案 1 :(得分:1)
[i for sublist in bonds for i in sublist]
答案 2 :(得分:1)
其他方式,使用itertools
模块中的chain.from_iterable
:
>>> l = [(0.0, 0.99), (-30, 30), (-30, 30), (0.0, 30), (0.0, 30), (-0.99, 0.99)]
>>> bonds = list(itertools.chain.from_iterable(l*3))
>>> bonds
[0.0, 0.99, -30, 30, -30, 30, 0.0, 30, 0.0, 30, -0.99, 0.99, 0.0, 0.99, -30, 30, -30, 30, 0.0, 30, 0.0, 30, -0.99, 0.99, 0.0, 0.99, -30, 30, -30, 30, 0.0, 30, 0.0, 30, -0.99, 0.99]
编辑:比较一些表达的速度,我尝试了以下内容:
$ python3 -mtimeit -s 'l = [(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99)]' 'bonds=list(itertools.chain.from_iterable(l*3))'
1000000 loops, best of 3: 1.95 usec per loop
$ python3 -mtimeit -s 'l = [(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99)]' 'bonds = l*3'
10000000 loops, best of 3: 0.147 usec per loop
$ python3 -mtimeit -s 'l = [(0., 0.99),(-30, 30),(-30, 30),(0., 30),(0., 30),(-0.99, 0.99)]' 'bonds=list(itertools.chain(l*3))'
1000000 loops, best of 3: 0.859 usec per loop
正如人们所注意到的,bonds = l*3
是上述表达式中最快的。