Python:根据条件插入数组

时间:2015-05-14 02:35:22

标签: python arrays indexing

以下代码产生此错误:

Traceback (most recent call last):
  File "pulllist2.py", line 28, in <module>
    list_sym[w] = symbol
IndexError: list assignment index out of range

如果word1word2位于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

3 个答案:

答案 0 :(得分:2)

你已经在这里初始化了你的列表,虽然是一个空列表:

list_sym = []

这很好,但是,当您添加到列表时会发生什么?您只需使用append方法。

list_sym.append(whatever)

看起来你来自旧语言(Java或C或C ++)。一切都有大括号和固定阵列长度和无聊的东西。您不必索引所做的一切。

append列表,只需添加到列表中即可。您可以向列表中添加任何内容。

list_sym.append(5345034750439)
list_sym.append("Yo. What's up!")

这对你来说更安全,因为你可以添加,而不是尝试获得一个位置。追加是要走的路。

找到长度:

>>> len(list_sym)
10 # There's 10 objects in the list.

让我向你推荐字典,就像我说的那样:

字典允许您将对象组合在一起,就像分配变量一样。就这么简单:

my_dictionary = {}

要添加对象,您需要密钥和价值。

my_dictionary["name"] = "Zinedine"
                ^           ^
               Key         Value

要访问该值,您需要知道密钥(如何在没有金钥匙的情况下获得宝藏)。就像你试图索引列表一样,你可以通过相同的概念获得价值。字典通常用于配对对象,或在共同范围下存储多个变量。希望对你有帮助! :)

答案 1 :(得分:0)

你不能在python中这样做。 尝试改为

list_sym.append(symbol)
list_name.append(security_name)

答案 2 :(得分:0)

我认为代码不必要地复杂化。我认为你正在努力与...联系。具有安全名称的符号,并且还希望将符号和安全名称分别作为列表。 regexp在这里可能是一个好主意。

import re
r = re.compile(r'Stock|ETF')
list_sym = {} # NOTE: A dict - keys symbols, values security names
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 r.match(security_name): # something matches 
            # stores values in array
            list_sym[symbol.lower()] = security_name # just to be safe

symbols = list_sym.keys()
security_names = list_sym.values()

这大致解释了这个想法。可能需要进行一些编辑才能尝试实现您的目标。

相关问题