Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表索引错误_Python_List - Fatal编程技术网

Python 列表索引错误

Python 列表索引错误,python,list,Python,List,我创建了一个程序,可以将文件行读入列表。当我运行下面的代码时,我看到有一个包含元素的列表 dogs_list_player = [] dogs_list_computer = [] with open("dogs.txt") as f: for i in range(Y): dogs_list_player.append(f.readline().splitlines()) print(dogs_list_player) for i in ran

我创建了一个程序,可以将文件行读入列表。当我运行下面的代码时,我看到有一个包含元素的列表

dogs_list_player = []
dogs_list_computer = []

with open("dogs.txt") as f:
    for i in range(Y):
        dogs_list_player.append(f.readline().splitlines())
        print(dogs_list_player)
    for i in range(Z):
        dogs_list_computer.append(f.readline().splitlines())
        print(dogs_list_computer)
结果是:

[['Tim']]
[['Tim'], ['Bob']]
[['Tim'], ['Bob'], ['Jess']]
[['Tim'], ['Bob'], ['Jess'], ['Bess']]
[['Tim'], ['Bob'], ['Jess'], ['Bess'], ['Tess']]
[['Dom']]
[['Dom'], ['Tom']]
[['Dom'], ['Tom'], ['Will']]
[['Dom'], ['Tom'], ['Will'], ['Ben']]
[['Dom'], ['Tom'], ['Will'], ['Ben'], ['Joe']]
但当我添加这部分代码时,问题就出现了:

dogs_list_player = []
dogs_list_computer = []

with open("dogs.txt") as f:
    for i in range(Y):
        dogs_list_player.append(f.readline().splitlines())
        print(dogs_list_player)
    for i in range(Z):
        dogs_list_computer.append(f.readline().splitlines())
        print(dogs_list_computer)

class Dog_card: 
    name  = ""
    friendliness = ""
    intelligence = ""
    exercise = ""
    drool = ""

    def printing_card(self):
        prnt_str = "Name:%s \nIntelligence:%s \nExercise:%s \nDrool:%s" %(self.name, self.friendliness, self.intelligence, self.exercise, self.drool)
        return prnt_str

player_card = Dog_card()
card_count = 0
player.name = dogs_list_player[0]#i think this is where the issue is happening
该代码的结果是:

IndexError: list index out of range

非常感谢您的帮助

您的Dog_card类出现一些错误: 您忘记了printing_card方法中字符串中的Friendlity参数,并且您的类中没有任何构造函数

class Dog_card:

def __init__(self):
    self.name = ""
    self.friendliness = ""
    self.intelligence = ""
    self.exercise = ""
    self.drool = ""

def printing_card(self):
    prnt_str = "Name:%s \nIntelligence:%s friendliness:%s \nExercise:%s \nDrool:%s" %(self.name, self.friendliness, self.intelligence, self.exercise, self.drool)
    return prnt_str

这应该是可行的。

试着打印狗列表播放器或借书人列表播放器,看看问题出在哪里。。。顺便说一句,您的类实际上应该在def uu init uu self:函数中稳定其属性,这样您就可以实际拥有多个具有不同属性的实例。what is Y-what is Z-两者都使用,但在代码中没有任何设置。你使用类成员,阅读关于和-第一个是在实例之间共享的,你不希望多个狗都有相同的名称。请提供@pekapa我已经尝试打印狗列表,我已经显示了上面的结果,但出于某种原因,我一直得到错误