简体   繁体   中英

Why all are indexes in my list of lists 0?

I want a flashcard software with decks and cards. I created a general list all_decks. I created a class for the decks:

 class deck(list): 
    def __init__(self, name):
            self.name = name
    def open_deck(self):
            print "This is your deck %s: " %(self.name)
            print "This deck has %s cards." %(len(self)) 
            return self

The deck is then created with user input for the name and appended to all_decks. This is the function to print them:

def print_decks():                                                      
    print "You have %s decks: " %(len(all_decks))
    for x in all_decks:
            print all_decks.index(x), x.name

This does print a list of all the decks, but all indexes appear to be 0. Why? Also I thought I would use indexes for the "open deck" and "delete deck" functions but it's not working.

You've misunderstood what index() does. It returns the index of the first element in the list that matches your target. But you never defined a way of comparing decks.

You don't really want to use index here. Instead, keep count with enumerate :

for i, x in enumerate(all_decks):
        print i, x.name

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