使用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完成了数组中的所有操作,我想知道是否有类似的内容。
答案 0 :(得分:155)
是的,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] #=> []
答案 1 :(得分:25)
如果要在索引i上拆分/剪切数组,
arr = arr.drop(i)
> arr = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
> arr.drop(2)
=> [3, 4, 5]
答案 2 :(得分:16)
您可以使用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)。
答案 3 :(得分:6)
另一种方法是使用范围方法
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]
答案 4 :(得分:5)
Ruby 2.6无穷无尽的范围
(..1)
# or
(...1)
(1..)
# or
(1...)
[1,2,3,4,5,6][..3]
=> [1, 2, 3, 4]
[1,2,3,4,5,6][...3]
=> [1, 2, 3]
ROLES = %w[superadmin manager admin contact user]
ROLES[ROLES.index('admin')..]
=> ["admin", "contact", "user"]
答案 5 :(得分:0)
我喜欢这个范围:
def first_half(list)
list[0...(list.length / 2)]
end
def last_half(list)
list[(list.length / 2)..list.length]
end
但是,要非常小心端点是否包含在您的范围内。这在一个奇怪的长度列表中变得至关重要,你需要选择在哪里打破中间位置。否则你最终会重复计算中间元素。
以上示例将始终将中间元素放在后半部分。
答案 6 :(得分:-4)
你也可以写这样的东西
foo = [1,2,3,4,5,6,7]
bar = [10,20,30,40,50,60,70]
half = foo.length / 2
foobar = (foo.first half) + (bar.drop half)
=> [1, 2, 3, 40, 50, 60, 70]