Day07

一:list 扩充

关于列表遍历删除得问题:

代码演示:

list = [11,22,33,44,55]
for i in range(len(list)):
    print(i)
    del (list[i])
    print(list)

运行结果:

D:\常用软件\Python3.7\python文件\python.exe "D:\常用软件\Pycharm\pycharm文件\PyCharm 5.0.3\helpers\pydev\pydevd.py" --multiproc --qt-support --client 127.0.0.1 --port 8961 --file D:/学习资料/项目/练习/lianxi.py
pydev debugger: process 3240 is connecting

Connected to pydev debugger (build 143.1559)
0
[22, 33, 44, 55]
1
[22, 44, 55]
2
[22, 44]
3
Traceback (most recent call last):
  File "D:\常用软件\Pycharm\pycharm文件\PyCharm 5.0.3\helpers\pydev\pydevd.py", line 2407, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "D:\常用软件\Pycharm\pycharm文件\PyCharm 5.0.3\helpers\pydev\pydevd.py", line 1798, in run
    launch(file, globals, locals)  # execute the script
  File "D:\常用软件\Pycharm\pycharm文件\PyCharm 5.0.3\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc) 
  File "D:/学习资料/项目/练习/lianxi.py", line 4, in <module>
    del (list[i])
IndexError: list assignment index out of range

进程已结束,退出代码1

分析:

报错得主要原因是:每次删掉一个列表中得元素得时候,比如[11,22,33,44,55] 第一次删除11的时候,22就会往前面进一位,这就造成了22这个元素它的索引发生了改变,所以再删除的时候就会发生索引溢出从而出错。所以不要遍历删除索引。

二、集合(set)

        python中的集合是可变的数据类型,但是它里面存储的数据是不可变的数据类型,无序,且不能够重复。

  

posted @ 2020-02-16 16:38  江湖混子  阅读(151)  评论(0编辑  收藏  举报