jay*_*ydh 4 python split list python-2.7
我有两个清单:l1 = [0, 0.002, 0.3, 0.5, 0.6, 0.9, 1.3, 1.9]
和l2 = [0.5, 1.0, 1.5, 2.0]。我想拆分l1为定义为的两个索引之间的元素的子列表l2。因此,例如l1等于[[0,0.002, 0.3], [0.5, 0.6, 0.9], [1.3], [1.9]]。
这是我的解决方案:
l3 = []
b=0
for i in l2:
temp = []
for p in l1:
if b <= p < i:
temp.append(p)
l3.append(temp)
b+=0.5
Run Code Online (Sandbox Code Playgroud)
此解决方案是我的代码中的巨大瓶颈。有更快的方法吗?
您的列表已排序,因此这里无需进行双循环。
以下基于两个列表作为输入生成子列表:
def partition(values, indices):
idx = 0
for index in indices:
sublist = []
while idx < len(values) and values[idx] < index:
sublist.append(values[idx])
idx += 1
if sublist:
yield sublist
Run Code Online (Sandbox Code Playgroud)
然后,您可以遍历partition(l1, l2)以获取单个子列表,或者调用一次list()即可生成整个列表:
>>> l1 = [0, 0.002, 0.3, 0.5, 0.6, 0.9, 1.3, 1.9]
>>> l2 = [0.5, 1.0, 1.5, 2.0]
>>> list(partition(l1, l2))
[[0, 0.002, 0.3], [0.5, 0.6, 0.9], [1.3], [1.9]]
Run Code Online (Sandbox Code Playgroud)