列表索引超出范围如何解决

时间:2019-08-23 10:03:13

标签: python pycharm range

我遇到一个问题,指出列表索引超出范围

如何解决?

<div class="container-flex">
    <div class="row">
        <div class="col-12 col-md-6 col-lg-3">1</div>
        <div class="col-12 col-md-6 col-lg-3">2</div>
        <div class="col-12 col-md-6 col-lg-3">3</div>
        <div class="col-12 col-md-6 col-lg-3">4</div>
    </div>
</div>

这是“ combo.txt” 它在此表格email:pass

combo_list=[]
_combo_ = open("combo.txt", "r").readlines()
_combo_new = [items.rstrip() for items in _combo_]
for lines in _combo_new:
    new_lines = lines.split(":")
    combo_list.append({"username": new_lines[0],
                            "password": new_lines[1]})
    print(combo_list)

我收到此错误

[{'username': 'kazut@app-expert.com', 'password': 'kazut@app-expert.com'}

1 个答案:

答案 0 :(得分:0)

如果您split(':')在此行[{'username': 'kazut@app-expert.com', 'password': 'kazut@app-expert.com'}中,结果将是具有以下值的列表:

  1. "[{'username'"
  2. "'kazut@app-expert.com', 'password'"
  3. "'kazut@app-expert.com'}"

如果您不想将数据解析为json,则对split('\'')这样做更安全:

combo_list=[]
_combo_ = open("a.txt", "r").readlines()
_combo_new = [items.rstrip() for items in _combo_]
for lines in _combo_new:
    new_lines = lines.split("\'")
    combo_list.append({"username": new_lines[3],
                            "password": new_lines[7]})
    print(combo_list)