下面的代碼是生產這個錯誤:的Python:插入陣列根據病情
Traceback (most recent call last):
File "pulllist2.py", line 28, in <module>
list_sym[w] = symbol
IndexError: list assignment index out of range
我想在這裏實現的是隻有一個元素添加到數組,如果word1
和word2
是串中security_name
。我不知道另一種方法來初始化數組。
#!/usr/bin/env python3
import glob
import os
import sys
import fnmatch
list_sym = []
list_name = []
w = 0
count = 0
word1 = 'Stock'
word2 = 'ETF'
# for loop that parses lines into appropriate variables
for file in glob.glob('./stocklist/*.txt'):
with open(file) as input:
for line in input:
# split line into variables.. trash will have no use
symbol, security_name, trash = line.split('|', 2)
if word1 in security_name or word2 in security_name:
# stores values in array
list_sym.append(1) ## initialize arrays
list_name.append(1)
list_sym[w] = symbol
list_name[w] = security_name
count += 1
w += 1
爲什麼在使用字典時使用並行列表?你已經在開始時初始化了你的數組。同樣,你的for循環也不對。你不能訪問'文件對象'中的'行'。 – Zizouz212
看着字典的權利,謝謝你的提示。 –