gpt4 book ai didi

python - 在有序列表中的点之前、之后和之间计数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:58:55 25 4
gpt4 key购买 nike

我正在尝试创建一个算法来计算有序列表中某些点之前、之后和之间的多个计数。这里我的“某些点”是需要附加到 x 值并排序的 y 值。这是我正在尝试做的事情的简单说明。

x = [2,3,5,6,7,9]
y = [1,4,10]

# appending y to x and ordering gives us:
full_list = [1,2,3,4,5,6,7,9,10]

因此对于 y = 1,指标将通过按如下方式切片 full_list 以非编程方式计算:

num_between_before = len(full_list[0:0])
0
num_between_after = len(full_list[0:4])
2
num_before = len(full_list[0:0])
0
num_after = len(full_list[0:9])
8

但当然,我正在尝试以编程方式对始终为数字的任何列表 x 和也始终为数字的任何列表 y 执行此操作。 x 和 y 可以是任意大小,但 len(y) < len(x)。完整有序列表的 y 值可以分布在 x 值之间的任何位置。

以编程方式输出可能如下所示:

# y_val: (num_between_before, num_between_after, num_before, num_after)
output:
1: (0, 2, 0, 8)
4: (2, 4, 3, 5)
10: (4, 0, 8, 0)

显然,到目前为止,我在我的代码中遇到了问题:

x = [1434684599341,1434684606154,1434684607190,1434684613843,1434684677605,
1434684704358,1434684708727,1434684724495,1434684758413,1434684782632]

y = [1434471725039, 1434684613844, 1434684708728, 1434684782633]

y.sort()

for i in y:
x.append(i)

x.sort()

idx = []
for j in y:
idx.append(x.index(j))

counter = 0

for i, k in zip(idx, y):

counter += 1
if i == 0:
before = len(x[i:i])
after = len(x[i:conv_index[counter]]) - 1
print before, after
elif i == idx[-1]:
before = len(x[i-counter:idx[counter-1]]) - 1
after = len(x[i:i])
print before, after
else:
before = len(x[i:idx[counter]])
after = len(x[i:idx[counter]]) - 1
print before, after

最佳答案

如果我关注你,我认为这可行:

def allCounts(x,y):
z = x+y
z.sort()
d = {}
for i in y:
d[i] = z.index(i)
counts = {}
for i,j in enumerate(y):
if i == 0:
counts[j] = (0,d[y[i+1]]-d[j]-1,d[j],len(z)-d[j]-1)
elif i < len(y) - 1:
counts[j] = (d[j]-d[y[i-1]]-1,d[y[i+1]]-d[j]-1,d[j],len(z)-d[j]-1)
else:
counts[j] = (d[j]-d[y[i-1]]-1,0,d[j],len(z)-d[j]-1)
return counts

用你的测试数据:

>>> x = [2,3,5,6,7,9]
>>> y = [1,4,10]
>>> c = allCounts(x,y)
>>> c
{1: (0, 2, 0, 8), 10: (4, 0, 8, 0), 4: (2, 4, 3, 5)}

关于python - 在有序列表中的点之前、之后和之间计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com