python - 索引错误 : list index out of range python 3. 6

标签 python python-3.x

我有以下代码

def retrieve_user(username):

    with open(users_file, 'r', encoding='utf-8') as f:

        items = []
        line_num = 0
        for line in f:
            line_num = line_num+1
            #print(items)
            if line_num > 1:
                items = line.split(';')
                name = items[0]
                area = items[1]
                all_keywords = items[2].split('$')

                if name in user.keys():
                    user[name].append([area, all_keywords])
                else:
                    user[name] = [area, all_keywords]

        if username in user.keys():
            print(user[username])
        else:
            print('User ', username, ' could not be found')
            login_user()

    return False

现在我收到以下错误。有人知道为什么吗?我陷入困境,我不知道我做错了什么。

**area = items[1]
IndexError: list index out of range**

我尝试检索数据的文件如下所示

user;area;keywords

mike;Sports: Football;Arsenal

john;Technology: IBM;CPU

提前谢谢

最佳答案

如果您在 上拆分空行,则文件中有空行; 您在生成的 item 中没有索引 1。错误告诉了你这么多。

您的代码缺少关键代码部分(例如用户字典):

试试这个:

with open(users_file, 'r', encoding='utf-8') as f:
   txt = f.read()

# txt = """user;area;keywords
#
# mike;Sports: Football;Arsenal
# 
# john;Technology: IBM;CPU"""

# split each line on newlines, take only lines thats have non-whitespace in it. 
# split those line at ;
splitted = [x.split(";") for x in txt.splitlines() if x.strip() != ""]
print(splitted)

输出:

[['user', 'area', 'keywords'], 
 ['mike', 'Sports: Football', 'Arsenal'], 
 ['john', 'Technology: IBM', 'CPU']]

按行访问已解析的列表:

for name, area, words in splitted[1:]:  # skips the first row via list comprehension, 
                                        # and decompose each inner list into name,
                                        # area and words
    all_keywords = words.split("$")
    print(name, "    ", area , "    ", all_keywords)

输出:

mike      Sports: Football      ['Arsenal']
john      Technology: IBM      ['CPU']

如果您想在字典中创建键,您可以利用dict.setdefault(key,defaultvalue):

if name in user.keys():
    user[name].append([area, all_keywords])
else:
    user[name] = [area, all_keywords]

大致相当于:

user.setdefault(name,[]).extend([area, all_keywords])  

如果该键尚不存在,则会创建一个带有空列表的键。该值由 setdefault 返回,并且 extend(...) 添加您当前的数据。如果键存在,setdefault 简单地返回该值并扩展它。双赢:您的名单不断增长。

参见https://docs.python.org/3/library/stdtypes.html#dict或这个答案:https://stackoverflow.com/a/3483652/7505395

关于python - 索引错误 : list index out of range python 3. 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48270571/

相关文章:

python - 如何在不阻塞事件循环的情况下迭代一个大列表

python - 如何在Django中的表单验证中排除某些字段

python - 为什么单引号( ' ) and double quote( ")在 python 的 json 模块中得到不同的结果?

python - 如何修复scrapy源码测试失败: FifoDiskQueue

python - 应用具有两个不同列表的公式

python - 覆盖子类 Python 枚举中的方法

python - 关闭不传递值。 python 3

python - 具有昂贵计算的列表理解

python - 将 Spyder IDE 图形窗口置于前面

python - 仅当所有元素都是 pandas 的 groupby 中的 NA 时,如何删除 NA