当前位置 博文首页 > python切片中内存的注意事项总结

    python切片中内存的注意事项总结

    作者:小妮浅浅 时间:2021-09-18 18:41

    1、由于 Python 列表的切片会在内存中创建新对象,因此需要注意的另一个重要函数是itertools.islice。

    2、通常需要遍历切片,而不仅仅是在内存中静态创建它。islice非常适合这个。

    一个警告,它不支持负的参数start,stop或者step,如果这是一个问题,您可能需要计算指标或反向迭代提前。

    length = 100
    last_nine_iter = itertools.islice(list(range(length)), length-9, None, 1)
    list_last_nine = list(last_nine_iter)

    现在:

    >>> list_last_nine
    [91, 92, 93, 94, 95, 96, 97, 98, 99]

    列表切片制作副本的事实是列表本身的一个特征。如果您对 Pandas DataFrame 等高级对象进行切片,它可能会返回原始视图,而不是副本。

    内容扩展:

    语法:

    nuList[start:end:direction]
    start -->起始下标(direction = 1时,默认是0;direction = -1时默认是-1)
    start -->结束下标(direction = 1时,默认是len(nuList)-1;direction = -1时默认是-(len(nuList)-1))
    direction --> 默认是1,切片方向从左往右;-1时,切片方向从右往左

    1.只包含左边的端数据,不包含右边的端数据

    print(nuList[1:3])

    结果是:[1,2]

    2.按照不同的方向返回元素

    print(nuList[::])

    结果是:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    print(nuList[::-1])

    结果是:[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

    3.严格按照方向顺序截取

    print(nuList[3:1]) #从左往右,下标3开始切,但是无法找到下标1

    print(nuList[-1:-3]) #从左往右,下标-1开始切,但是无法找到下标-3

    print(nuList[-3:-1:-1]) #从右往左,下标-3开始切,但是无法找到下标-1

    结果都为:[]

    print(nuList[1:-1]) #从左往右,下标1开始切,能找到-1下标

    结果:[1, 2, 3, 4, 5, 6, 7, 8]

    print(nuList[-1:1:-1]) #从右往左,下标-1开始切,能找到1下标

    结果:[9, 8, 7, 6, 5, 4, 3, 2]

    jsjbwy
    下一篇:没有了