【python基础】list操作相关:扩充、条件查找【IndexError: list assignment index out of range】

参考

https://blog.csdn.net/qq_44768814/article/details/88614393

【IndexError: list assignment index out of range】

报错原因就是list的扩充 要使用append 或者 extend,而不能直接list[i]去添加。

比如

# 错误的list扩充方式 会报错
a=[]
for i in range(0,5):
    a[i]=i

# IndexError: list assignment index out of range

# 正确的list扩充 append
a=[]
for i in range(0,5):
    a.append(i)

# 输出:
a
# [0, 1, 2, 3, 4]

# 正确的list扩充 extend 用来把list1扩充到list2上
a=[]
b=[[1,2,3],[11,22,33],[111,222,333]]
for i in range(0,3):
    a.extend(b[i])
# 输出
a
# [1, 2, 3, 11, 22, 33, 111, 222, 333]

 

二、list的条件查找

a=[1,2,3]

a.index(3)

 

posted @ 2019-09-17 10:20  anno_ym雨  阅读(4371)  评论(0编辑  收藏  举报