按其值将文件中的数字追加到列表中



我有一个包含数值的文件:

1
4
6
10
12

我正在尝试将这些值附加到数组中的相应位置,我将在其中获得:

[None,1,None,None,4,None,6,None,None,None,10,None,None,12]

由于文件中的 1 将位于列表中的索引1,因此文件中的 4 将位于列表中的索引 4,依此类推。

我首先阅读文件:

filename = open("numbers.txt", "r", encoding = "utf-8")
numfile = filename
lst = [None] * 12
for line in numfile:
line = line.strip()   #strip new line
line = int(line)       #making the values in integer form  
vlist.append(line)   #was thinking of line[val] where value is the number itself.
print(vlist)

但我得到输出:

[None,None,None,None,None,None,None,None,None,1,4,6,10,12]

其中数字追加到数组的最右侧。将不胜感激。

假设您在名为numbers的列表中将数字作为integers(您看起来没有问题(,您可以执行以下操作:

lst = [None if i not in numbers else i for i in range(max(numbers)+1)]

如果numbers可以成为一个大列表,我会先把它投给set,以便更快地进行in比较。

numbers = set(numbers)
lst = [None if i not in numbers else i for i in range(max(numbers)+1)]

>>> numbers = [1, 4, 6, 10, 12]
>>> [None if i not in numbers else i for i in range(max(numbers) + 1)]
[None, 1, None, None, 4, None, 6, None, None, None, 10, None, 12]

追加到列表会将数字添加到列表的末尾。相反,您希望将line的值分配给

索引处的列表line
filename = open("numbers.txt", "r", encoding = "utf-8")
numfile = filename
lst = [None] * 13
for line in numfile:
line = line.strip()   #strip new line
line = int(line)       #making the values in integer form  
lst[line] = line  
print(lst)
# [None, 1, None, None, 4, None, 6, None, None, None, 10, None, 12]

可以使用索引器并将其值与行的实际值进行比较,并替换索引处的值,而不是

filename = open("numbers.txt", "r", encoding = "utf-8")
numfile = filename
lst = [None] * 12
i = 0
for line in numfile:
line = line.strip()   #strip new line
line = int(line)       #making the values in integer form  
value = None
if (i == line):
value = line
if (len(vlist) < line): #replace or append if there's more numbers in the file than the size of the list
vlist[i] = value
else:
vlist.append(value) 
i += 1
print(vlist)

在循环中追加到列表的成本很高。我建议您构建一个None项列表,然后迭代列表以更新元素。

下面是一个带有itertoolscsv.reader的演示:

from io import StringIO
from itertools import chain
import csv
mystr = StringIO("""1
4
6
10
12""")
# replace mystr with open('numbers.txt', 'r')
with mystr as f:
reader = csv.reader(f)
num_list = list(map(int, chain.from_iterable(reader)))
res = [None] * (num_list[-1]+1)
for i in num_list:
res[i] = i
print(res)
[None, 1, None, None, 4, None, 6, None, None, None, 10, None, 12]

基准测试示例:

def appender1(n):
return [None]*int(n)
def appender2(n):
lst = []
for i in range(int(n)):
lst.append(None)
return lst
%timeit appender1(1e7)  # 90.4 ms per loop
%timeit appender2(1e7)  # 1.77 s per loop

最新更新