通过文件的值

时间:2018-05-16 09:32:55

标签: python

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

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]

数字附加到数组的最右侧。希望得到一些帮助。

4 个答案:

答案 0 :(得分:2)

假设您在名为int的列表中将您的号码设为numbers egers(,您似乎没有问题),您可以执行以下操作:

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]

答案 1 :(得分:0)

附加到列表会在列表末尾添加数字。您希望将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]

答案 2 :(得分:0)

在循环中追加列表很昂贵。我建议你的构造一个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

答案 3 :(得分:0)

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

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)