简体   繁体   English

根据列表检查输入并附加到列表列表

[英]Checking inputs against list and appending to list of lists

I have an unordered list, A = [1, 4, 16, 22, 9, 2] and an ordered list p = [0, 6, 12] .我有一个无序列表A = [1, 4, 16, 22, 9, 2]和一个有序列表p = [0, 6, 12]

I have created a list of lists s = [ [] for i in range(n+1)] .我创建了一个列表列表s = [ [] for i in range(n+1)]

I want to compare each element of A against the first element in p , then the second and so on.我想将A每个元素与p中的第一个元素进行比较,然后是第二个,依此类推。

If A's element is smaller than p's element I want to append this to the correct list in s .如果A's元素小于p's元素,我想将其附加到s的正确列表中。 (so first list in s will be empty as nothing is smaller than 0, second list in s should hold 1,4,2. -- Eventually 0 will go into the first list, 6 into the second and 12 into the third. The fourth list will hold elements greater than 12. (所以s第一个列表将是空的,因为没有小于 0 的值, s第二个列表应该包含 1,4,2。--最终 0 将进入第一个列表,6 进入第二个列表,12 进入第三个列表。第四个列表将包含大于 12 的元素。

(I need it to be generic and work for different list sizes, so A could hold 20 elements and p could hold 5 etc..) (我需要它是通用的并且适用于不同的列表大小,所以A可以容纳 20 个元素, p可以容纳 5 个等等。)

I'm struggling to put this into action.我正在努力将其付诸行动。 Please help!请帮忙!

Since p is sorted, you can use bisect for this (with O(log(N)) complexity):由于p已排序,您可以为此使用bisect (复杂度为O(log(N)) ):

for a in A:
    s[bisect.bisect_left(p, a)].append(a)

Out:出去:

[[], [1, 4, 2], [9], [16, 22]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM