简体   繁体   中英

TypeError: 'type' object is not subscriptable. How can I get this to remove an array from a 2d array?

I have had a look at answers to similar questions but I just can't make this work. I am quite new to python.

def read():

    set = []
    f = open("error set 1.txt", "r")
    replace = f.read()
    f.close()

    f = open("Test1_Votes.txt", "w")
    replaced = replace.replace(",", "")
    f.write(replaced)
    f.close()



    f = open("Test1_Votes.txt", "r")
    for line in f:
        ballot = []


        for ch in line:

            vote = ch

            ballot.append(vote)

        print (ballot)

        set.append(ballot)


    """print(set)"""
    remove()

def remove():
    for i in range (70):
        x = i - 1
        check = set[x]
        if 1 not in check:
            set.remove[x]
    print(set)

The error is line 37, check = set[x] I'm unsure of what is actually causing the error

In the remove function, you have not defined set . So, python thinks it's the built-in object set , which is actually not subscriptable.

Pass your object to the remove function, and, preferably, give it another name.

Your remove function cant "see" your set variable (which is list, avoid using reserved words as variable name), because its not public, its defined only inside read function. Define this variable before read function or send it as input to remove function, and it should be working.

def read():
    set = []
    f = open("error set 1.txt", "r")
    replace = f.read()
    f.close()

    f = open("Test1_Votes.txt", "w")
    replaced = replace.replace(",", "")
    f.write(replaced)
    f.close()

    f = open("Test1_Votes.txt", "r")
    for line in f:
        ballot = []


    for ch in line:
        vote = ch
        ballot.append(vote)

    print (ballot)

    set.append(ballot)


    """print(set)"""
    remove(set)

def remove(set):
    for i in range (70):
        x = i - 1
        check = set[x]
        if 1 not in check:
            set.remove(x)
    print(set)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM