use*_*358 8 python search list
我正在使用python.我有两个列表,列表1是7000个整数长,列表2是25000个整数.我想通过列表1中的每个数字,找到列表2中最接近的数字,这个数字更大,最接近的数字小于列表1中的每个数字,然后计算列表2中这两个数字之间的差异.到目前为止我有:
for i in list1:
for j in list 2:
if list2[j]<list1[i]:
a = max(list2)
elif list2[j]>list1[i]:
b = min(list2)
interval = b-a
Run Code Online (Sandbox Code Playgroud)
这似乎不起作用.我想在列表2中找到小于列表1中特定数字的明确数字并知道最大值,然后找出列表2中比列表1中的数字更大的最小数字.有没有人有任何想法?谢谢
你可以使用bisect模块,最坏情况的复杂性O(N * logN):
import bisect
lis1 = [4, 20, 26, 27, 30, 53, 57, 76, 89, 101]
lis2 = [17, 21, 40, 49, 53, 53, 53, 53, 70, 80, 81, 95, 99] #this must be sorted
#use lis2.sort() in case lis2 is not sorted
for x in lis1:
#returns the index where x can be placed in lis2, keeping lis2 sorted
ind=bisect.bisect(lis2,x)
if not (x >= lis2[-1] or x <= lis2[0]):
sm, bi = lis2[ind-1], lis2[ind]
if sm == x:
""" To handle the case when an item present in lis1 is
repeated multiple times in lis2, for eg 53 in this case"""
ind -= 1
while lis2[ind] == x:
ind -= 1
sm = lis2[ind]
print "{} <= {} <= {}".format(sm ,x, bi)
Run Code Online (Sandbox Code Playgroud)
输出:
17 <= 20 <= 21
21 <= 26 <= 40
21 <= 27 <= 40
21 <= 30 <= 40
49 <= 53 <= 70
53 <= 57 <= 70
70 <= 76 <= 80
81 <= 89 <= 95
Run Code Online (Sandbox Code Playgroud)
虽然这不会输出任何东西4和101,如图4比LIS2任何元件更小,101比任何LIS2元件更大.但如果需要,可以修复.
这是使用NumPy的矢量化解决方案.它应该非常快,因为它在Python中没有循环(除了最后的打印阶段).
import numpy as np
# set up fake data
l1 = np.array([1.9, 2, 2.1]) # or whatever list you have
l2 = np.array([1, 2, 5, 10]) # as above
l2.sort() # remove this line if it's always sorted
# the actual algorithm
indexes = np.searchsorted(l2, l1, side='right')
lower = l2[indexes - 1]
upper = l2[indexes]
diffs = upper - lower
# print results for debugging
for value, diff in zip(l1, diffs):
print "value", value, "gap", diff
Run Code Online (Sandbox Code Playgroud)
以下是带有硬编码测试数据的输出:
value 1.9 gap 1
value 2.0 gap 3
value 2.1 gap 3
Run Code Online (Sandbox Code Playgroud)
小智 4
首先,您的示例不是有效的代码,或者至少它没有执行您想要的操作。如果你有
for i in list1:
Run Code Online (Sandbox Code Playgroud)
那么 i 不是索引,而是 list1 的一个元素。所以首先你要比较 i 和 j,而不是 list[i] 和 list[j]。
使用列表理解应该更容易>
for i in list1:
a = max([n for n in list2 if n < i])
b = min([n for n in list2 if n > i])
Run Code Online (Sandbox Code Playgroud)
您可能需要添加一个或两个 if 来确保 a 和 b 存在,但它应该像这样工作。
| 归档时间: |
|
| 查看次数: |
1222 次 |
| 最近记录: |