gpt4 book ai didi

python - 字典似乎没问题,但函数返回 "List index out of range"

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:59 25 4
gpt4 key购买 nike

我不确定为什么这个函数返回“列表索引超出范围”,因为它看起来没问题。该函数所做的基本上是使用 file.txt 的内容来创建一个包含值的字典。

恢复,该函数将转换file.txt的内容:

access_1;test_group_1,test_group_2

到:

[{'groups': 'test_group_1,test_group_2\n', 'acl': 'access_1'}

当前代码:

def prepare_list():
try:
input_list = []
ins = open("file.txt", "r")
for line in ins:
values = dict()
values['acl'] = line.split(";")[0]
values['groups'] = line.split(";")[1]
input_list.append(values)
except Exception, e:
print "Error : %s" % e
finally:
return input_list

输出:

Error : list index out of range

Process finished with exit code 0

我在文件所在的文件夹上运行脚本。

最佳答案

data = "a;b"
print data.split(";") # Prints ['a', 'b']
data = "ab"
print data.split(";") # Prints ['ab']
print data.split(";")[1] # raises IndexError: list index out of range

因此,如果 ; 不存在,它将只返回一个元素。如果您尝试访问第二个元素,它将因该错误而失败。

如果你确定,所有行都会有 ;,你的整个程序可以这样写

keys = ("acl", "groups")
with open("Input.txt", "r") as ins:
input_list = [{k:v for k, v in zip(keys,l.rstrip().split(";"))} for l in ins]
print input_list

关于python - 字典似乎没问题,但函数返回 "List index out of range",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21219792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com