我们有一个元素 = 0 的列表,例如:
A = [0 for x in range (35)]
该列表填充了 35 个零。
我有几个列表,其中包含要使用的文件中的范围(大约 5 个):示例:
15 20
20 3
12 5
5 1
7 22
for i in file:
start_elem = min(i[0], i[1])
end_elem = max(i[0], i[1]) #Here it takes the maximum and minimum values from the table from the file.
而且我需要在每个循环“for”之后,他将单位添加到我的列表中,其中我有零,按索引,在循环中指示(start_elem,end_elem)。此选项不起作用:
for j in A[int(start_elem):int(end_elem)]:
j+=1
print(A)
结论应该是这样的
[0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 0, 0]
我的代码是:
L = [0 for j in range (36)]
for i in file:
start_elem = min(i[0], i[1])
end_elem = max(i[0], i[1])
for j in L[int(start_elem):int(end_elem)]:
j+=1
print(L)
file_new.write(str(L))
gen_file.closed
gen_file_new.closed
Python 列表列表不是解决此问题的数据结构的好选择,因为您正在更新 Python 级嵌套循环中的值。如果您可以使用 3rd 方库,则可以使用 NumPy 执行此操作:
import numpy as np
from io import StringIO
x = StringIO("""15 20
20 3
12 5
5 1
7 22""")
# define array of zeros
A = np.zeros(35)
# replace x with 'file.csv'; load and sort indices
index_array = np.sort(np.loadtxt(x, dtype=int), axis=1)
# iterate array of sorted indices
for start, end in index_array:
A[start: end] += 1
array([ 0., 1., 1., 2., 2., 2., 2., 3., 3., 3., 3., 3., 2.,
2., 2., 3., 3., 3., 3., 3., 1., 1., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0.])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句