使用Python中的列表,我可以使用以下代码返回它的一部分:
foo = [1,2,3,4,5,6] bar = [10,20,30,40,50,60] half = len(foo) / 2 foobar = foo[:half] + bar[half:]
由于Ruby在数组中做了所有事情,我想知道是否有类似的东西.
是的,Ruby具有与Python非常相似的数组切片语法.以下是ri
数组索引方法的文档:
--------------------------------------------------------------- Array#[] array[index] -> obj or nil array[start, length] -> an_array or nil array[range] -> an_array or nil array.slice(index) -> obj or nil array.slice(start, length) -> an_array or nil array.slice(range) -> an_array or nil ------------------------------------------------------------------------ Element Reference---Returns the element at index, or returns a subarray starting at start and continuing for length elements, or returns a subarray specified by range. Negative indices count backward from the end of the array (-1 is the last element). Returns nil if the index (or starting index) are out of range. a = [ "a", "b", "c", "d", "e" ] a[2] + a[0] + a[1] #=> "cab" a[6] #=> nil a[1, 2] #=> [ "b", "c" ] a[1..3] #=> [ "b", "c", "d" ] a[4..7] #=> [ "e" ] a[6..10] #=> nil a[-3, 3] #=> [ "c", "d", "e" ] # special cases a[5] #=> nil a[6, 1] #=> nil a[5, 1] #=> [] a[5..10] #=> []
如果要在索引i上拆分/剪切数组,
arr = arr.drop(i) > arr = [1,2,3,4,5] => [1, 2, 3, 4, 5] > arr.drop(2) => [3, 4, 5]
你可以使用slice():
>> foo = [1,2,3,4,5,6] => [1, 2, 3, 4, 5, 6] >> bar = [10,20,30,40,50,60] => [10, 20, 30, 40, 50, 60] >> half = foo.length / 2 => 3 >> foobar = foo.slice(0, half) + bar.slice(half, foo.length) => [1, 2, 3, 40, 50, 60]
顺便说一下,据我所知,Python"列表"只是有效地实现了动态增长的数组.开头的插入是在O(n)中,最后插入是分摊O(1),随机访问是O(1).
另一种方法是使用范围方法
foo = [1,2,3,4,5,6] bar = [10,20,30,40,50,60] a = foo[0...3] b = bar[3...6] print a + b => [1, 2, 3, 40, 50 , 60]