List Slice in Python(Compared with Java)
Python:
在Python中, 对于list, 切片会返回一个新的list, 而不会改变原有的list. 注意这儿说的"不会改变原有的list"指的是下面的这种情况:
a = [10, 20, 30] b = a[1:3] print('a is {0}'.format(a)) print('b is {0}'.format(b)) print('Change b---------------') b[0] = 8 print('a is {0}'.format(a)) print('b is {0}'.format(b)) print('Change a---------------') a[1] = 1024 print('a is {0}'.format(a)) print('b is {0}'.format(b))
Output:
a is [10, 20, 30] b is [20, 30] Change b--------------- a is [10, 20, 30] b is [8, 30] Change a--------------- a is [10, 1024, 30] b is [8, 30]
从上面的代码以及输出结果中, 我们可以看出, 执行完"b = a[1:3]"后, 更改a或b中任何一个都不会对另外一个有影响.
请注意上面说的这种情况与下面这种情况的区别:
def change(x): x[1:3] = ['a', 'b'] a = [10, 20, 30] print('a is {0}'.format(a)) change(a) print('a is {0}'.format(a))
Output:
a is [10, 20, 30] a is [10, 'a', 'b']
Java:
现在让我们来看看Java中的'切片'操作(这里指的是List接口中的subList()方法)与Python中的切片操作的区别: (此处把
Java的subList()搬出来, 仅仅是为了对比一下,让大家更好的理解Python中的list切片"不会改变原有的list"这句话)
public static void main(String[] args){ List<Integer> alist = new ArrayList<Integer>(); for (int i = 0; i < 10; ++i){ alist.add(i); } List<Integer> blist = alist.subList(1, 5); System.out.println("alist:\n" + alist); System.out.println("blist:\n" + blist); System.out.println(); System.out.println("change alist----------------"); alist.set(1, 888); System.out.println("alist:\n" + alist); System.out.println("blist:\n" + blist); System.out.println(); System.out.println("change blist----------------"); blist.set(1, 1024); System.out.println("alist:\n" + alist); System.out.println("blist:\n" + blist); }
Output:
alist: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] blist: [1, 2, 3, 4] change alist---------------- alist: [0, 888, 2, 3, 4, 5, 6, 7, 8, 9] blist: [888, 2, 3, 4] change blist---------------- alist: [0, 888, 1024, 3, 4, 5, 6, 7, 8, 9] blist: [888, 1024, 3, 4]
从上面的代码以及输出结果中, 我们可以看出, 执行完"List<Integer> blist = alist.subList(1, 5);"后, 更改alist或blist中任何一个,
都会对另外一个有影响.