我有两个列表: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
这个解决方案是我代码中的一个巨大瓶颈。有没有更快的方法来做到这一点?
最佳答案
您的列表已排序,因此无需在此处进行双重循环。
以下基于两个列表作为输入生成子列表:
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
然后你可以迭代
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]]
关于Python - 根据另一个列表将列表拆分为子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32618390/