如何检查数组的值是否包含一个或多个值?

时间:2022-03-19 07:43:16

I'm looking to see if an array has one or more values inside it. For instance, something like so:

我在寻找一个数组中是否有一个或多个值。例如:

[1,2,3,4,5,6].include?([4,1])  # => true
[4,1,6,2].include?([4,1])  # => true
[3,4,7].include?([4,1])  # => false

Of course, the "include?" method can only check one value. Is there a method to check for multiple values?

当然,“include?”方法只能检查一个值。是否有方法检查多个值?

11 个解决方案

#1


16  

EDIT: I endorse Mark Thomas' alternate solution that uses the core Set class.

编辑:我支持马克·托马斯使用core Set类的替代解决方案。

While my solution more strictly answers the question at hand of how to do this with arrays, sjsc may benefit from reviewing his own case and exploring the option of using sets instead.

虽然我的解决方案更严格地回答了如何使用数组来解决这个问题,但是sjsc可能会受益于回顾他自己的案例并探索使用set的选项。

There are plenty of valid reasond to use arrays (maintaining order, allowing for duplicates), for which the below still suffices, but if none of these are involved, sjsc might actually benefit from using Set instead of Array, and to that extent, Mark's solution is semantically superior.

使用数组(保持顺序,允许重复)有很多有效的理由,对于这些理由,下面的仍然足够,但是如果不涉及其中任何一个,sjsc实际上可能从使用Set而不是数组中获益,在这个程度上,Mark的解决方案在语义上更优越。


I don't know of any library method that does this, but it wouldn't be too hard to write your own function.

我不知道有什么库方法可以做到这一点,但是编写自己的函数并不难。

class Array
  def subset?(a)
    (self - a).length == 0
  end
end

I'm sure there are computationally more efficient ways to accomplish this, but this should do what you're looking for.

我确信有更有效的计算方法来实现这一点,但是这应该可以实现您所期望的。

Doing array intersection works and basically amounts to the same thing.

做一个数组的交集,基本上是一样的。

class Array
  def subset?(a)
    (self & a).length == length
  end
end

Optimization at this level isn't going to help matters too much, but what you don't want to do is start comparing arrays multiple times:

在这个级别上的优化不会有太大的帮助,但是您不想做的是开始多次比较数组:

class Array
  # don't do this
  def subset?(a)
    (self & a) == a
  end
end

#2


57  

>> [1,2,3,4,5,6] & [4,1]
=> [1, 4]
>> [1,2,3,4,5,6] & [7,9]
=> []
>>

#3


25  

This is a set operation. Set is in the standard library.

这是一个集合操作。Set在标准库中。

require 'set'

a = Set[1,2,3,4,5,6]
b = Set[4,1]

b.subset? a
#=> true

#4


6  

A quick and dirty extension to @Schwartzie's approach:

对@Schwartzie方法的快速而肮脏的扩展:

larger_array = [1,2,3,4,5,6]
smaller_array = [4,1]
smaller_array.all? {|smaller_array_item| larger_array.include?(smaller_array_item)}

#5


4  

Base on kurumi and spyle's suggestion, here are my test:

根据kurumi和spyle的建议,以下是我的测试:

([1,2,3,4,5,6] & [4,1]).any? #=> true

([1、2、3、4、5、6]和[4 1]).any吗?# = >真

However, .any? will turn any objects to true

然而,.any吗?将任何对象变为true ?

([1,2,3,4,5,6] & [6,7]).any? #=> true

([1、2、3、4、5、6]和[6、7]).any吗?# = >真

So I think here might be a working one:

所以我认为这是一个有效的方法

([1,2,3,4,5,6] & [6,7]).length == [6,7].length #=> false

([1、2、3、4、5、6]和[6、7])。长度= =[6、7]。# = > false长度

( bigger_array & smaller_array ).length == smaller_array.length

(bigger_array & smaller_array)。长度= = smaller_array.length

#6


3  

What's wrong with [1,2,3,4,5,6].include?(4) and [1,2,3,4,5,6].include?(1)?

有什么问题(1、2、3、4、5、6]其中?(4)和(1、2、3、4、5、6]其中吗?(1)?

#7


2  

My conclusion is that the Subtraction method is generally nice, but actual Set objects are blazing fast since they are clearly optimized for this type of computation.

我的结论是减法通常是很好的,但是实际的集合对象是非常快的,因为它们显然是针对这种类型的计算而优化的。

Using this script: https://gist.github.com/1996001

使用这个脚本:https://gist.github.com/1996001

I got these benchmark results (on Ruby 1.9.2p290):

我得到了这些基准测试结果(Ruby 1.9.2p290):

SUBTRACTION
- subset
  0.180000   0.000000   0.180000 (  0.189767)
- partial subset
  0.170000   0.000000   0.170000 (  0.178700)
- non subset
  0.180000   0.000000   0.180000 (  0.177606)

INTERSECTION
- subset
  0.190000   0.000000   0.190000 (  0.194149)
- partial subset
  0.190000   0.000000   0.190000 (  0.191253)
- non subset
  0.190000   0.000000   0.190000 (  0.195798)

SET
- subset
  0.050000   0.000000   0.050000 (  0.048634)
- partial subset
  0.040000   0.000000   0.040000 (  0.045927)
- non subset
  0.050000   0.010000   0.060000 (  0.052925)

Which I consider pretty startling, especially if you check out the source:

我觉得这很令人吃惊,尤其是如果你看看资料来源:

# File 'lib/set.rb', line 204

def subset?(set)
  set.is_a?(Set) or raise ArgumentError, "value must be a set"
  return false if set.size < size
  all? { |o| set.include?(o) }
end

via: http://rubydoc.info/stdlib/set/1.9.2/Set#subset%3F-instance_method

通过http://rubydoc.info/stdlib/set/1.9.2/Set # % 3 f-instance_method子集

#8


2  

I like kurumi's answer, but just to throw one more out there:

我喜欢kurumi的回答,但我还想说一句:

>> set1 = [1,2,3,4,5,6]
[
    [0] 1,
    [1] 2,
    [2] 3,
    [3] 4,
    [4] 5,
    [5] 6
]
>> set2 = [4,1]
[
    [0] 4,
    [1] 1
]
>> set1.any?{ |num| set2.include?(num) }
true
>> set2 = [8,9]
[
    [0] 8,
    [1] 9
]
>> set1.any?{ |num| set2.include?(num) }
false

#9


1  

@kurumi has it right but I thought I'd add that I sometimes use this little extension when I only want a subset of an array (usually the hash keys though):

@kurumi说得对,但我觉得我应该补充一点,当我只想要一个数组的子集(通常是哈希键)时,我有时会使用这个小扩展:

class Hash
  # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3}
  def except(*keys)
    self.reject { |k,v|
      keys.include? k
    }
  end

  # Usage { :a => 1, :b => 2, :c => 3}.only(:a) -> {:a => 1}
  def only(*keys)
    self.dup.reject { |k,v|
      !keys.include? k
    }
  end
end

class Array
  def except(*values)
    self.reject { |v|
      values.include? v
    }
  end

  def only(*values)
    self.reject { |v|
      !values.include? v
    }
  end
end

#10


0  

Simple and best way :

简单而最好的方法:

([4,1] - [1,2,3,4,5,6]).empty? # => true

([4 1]-[1、2、3、4、5、6])空虚吗?# = >真

([4,1] - [4,1,6,2]).empty? # => true

([4 1]-[4 1 6,2])空虚吗?# = >真

([4,1] - [3,4,7]).empty? # => false

([4 1]-[3、4、7])空虚吗?# = >假

#11


0  

This will check whether an element exists in a array:

这将检查数组中是否存在元素:

students = ["jim", "bob", "sally"]
teachers = ["mrs. jones", "mrs. sharpe", "mrs. ray"]

puts "what's your name ?"
answer = gets.chomp

if answer.include?(students.to_s)
  puts "you are a student"

elsif
  puts "you are a teacher"

end

#1


16  

EDIT: I endorse Mark Thomas' alternate solution that uses the core Set class.

编辑:我支持马克·托马斯使用core Set类的替代解决方案。

While my solution more strictly answers the question at hand of how to do this with arrays, sjsc may benefit from reviewing his own case and exploring the option of using sets instead.

虽然我的解决方案更严格地回答了如何使用数组来解决这个问题,但是sjsc可能会受益于回顾他自己的案例并探索使用set的选项。

There are plenty of valid reasond to use arrays (maintaining order, allowing for duplicates), for which the below still suffices, but if none of these are involved, sjsc might actually benefit from using Set instead of Array, and to that extent, Mark's solution is semantically superior.

使用数组(保持顺序,允许重复)有很多有效的理由,对于这些理由,下面的仍然足够,但是如果不涉及其中任何一个,sjsc实际上可能从使用Set而不是数组中获益,在这个程度上,Mark的解决方案在语义上更优越。


I don't know of any library method that does this, but it wouldn't be too hard to write your own function.

我不知道有什么库方法可以做到这一点,但是编写自己的函数并不难。

class Array
  def subset?(a)
    (self - a).length == 0
  end
end

I'm sure there are computationally more efficient ways to accomplish this, but this should do what you're looking for.

我确信有更有效的计算方法来实现这一点,但是这应该可以实现您所期望的。

Doing array intersection works and basically amounts to the same thing.

做一个数组的交集,基本上是一样的。

class Array
  def subset?(a)
    (self & a).length == length
  end
end

Optimization at this level isn't going to help matters too much, but what you don't want to do is start comparing arrays multiple times:

在这个级别上的优化不会有太大的帮助,但是您不想做的是开始多次比较数组:

class Array
  # don't do this
  def subset?(a)
    (self & a) == a
  end
end

#2


57  

>> [1,2,3,4,5,6] & [4,1]
=> [1, 4]
>> [1,2,3,4,5,6] & [7,9]
=> []
>>

#3


25  

This is a set operation. Set is in the standard library.

这是一个集合操作。Set在标准库中。

require 'set'

a = Set[1,2,3,4,5,6]
b = Set[4,1]

b.subset? a
#=> true

#4


6  

A quick and dirty extension to @Schwartzie's approach:

对@Schwartzie方法的快速而肮脏的扩展:

larger_array = [1,2,3,4,5,6]
smaller_array = [4,1]
smaller_array.all? {|smaller_array_item| larger_array.include?(smaller_array_item)}

#5


4  

Base on kurumi and spyle's suggestion, here are my test:

根据kurumi和spyle的建议,以下是我的测试:

([1,2,3,4,5,6] & [4,1]).any? #=> true

([1、2、3、4、5、6]和[4 1]).any吗?# = >真

However, .any? will turn any objects to true

然而,.any吗?将任何对象变为true ?

([1,2,3,4,5,6] & [6,7]).any? #=> true

([1、2、3、4、5、6]和[6、7]).any吗?# = >真

So I think here might be a working one:

所以我认为这是一个有效的方法

([1,2,3,4,5,6] & [6,7]).length == [6,7].length #=> false

([1、2、3、4、5、6]和[6、7])。长度= =[6、7]。# = > false长度

( bigger_array & smaller_array ).length == smaller_array.length

(bigger_array & smaller_array)。长度= = smaller_array.length

#6


3  

What's wrong with [1,2,3,4,5,6].include?(4) and [1,2,3,4,5,6].include?(1)?

有什么问题(1、2、3、4、5、6]其中?(4)和(1、2、3、4、5、6]其中吗?(1)?

#7


2  

My conclusion is that the Subtraction method is generally nice, but actual Set objects are blazing fast since they are clearly optimized for this type of computation.

我的结论是减法通常是很好的,但是实际的集合对象是非常快的,因为它们显然是针对这种类型的计算而优化的。

Using this script: https://gist.github.com/1996001

使用这个脚本:https://gist.github.com/1996001

I got these benchmark results (on Ruby 1.9.2p290):

我得到了这些基准测试结果(Ruby 1.9.2p290):

SUBTRACTION
- subset
  0.180000   0.000000   0.180000 (  0.189767)
- partial subset
  0.170000   0.000000   0.170000 (  0.178700)
- non subset
  0.180000   0.000000   0.180000 (  0.177606)

INTERSECTION
- subset
  0.190000   0.000000   0.190000 (  0.194149)
- partial subset
  0.190000   0.000000   0.190000 (  0.191253)
- non subset
  0.190000   0.000000   0.190000 (  0.195798)

SET
- subset
  0.050000   0.000000   0.050000 (  0.048634)
- partial subset
  0.040000   0.000000   0.040000 (  0.045927)
- non subset
  0.050000   0.010000   0.060000 (  0.052925)

Which I consider pretty startling, especially if you check out the source:

我觉得这很令人吃惊,尤其是如果你看看资料来源:

# File 'lib/set.rb', line 204

def subset?(set)
  set.is_a?(Set) or raise ArgumentError, "value must be a set"
  return false if set.size < size
  all? { |o| set.include?(o) }
end

via: http://rubydoc.info/stdlib/set/1.9.2/Set#subset%3F-instance_method

通过http://rubydoc.info/stdlib/set/1.9.2/Set # % 3 f-instance_method子集

#8


2  

I like kurumi's answer, but just to throw one more out there:

我喜欢kurumi的回答,但我还想说一句:

>> set1 = [1,2,3,4,5,6]
[
    [0] 1,
    [1] 2,
    [2] 3,
    [3] 4,
    [4] 5,
    [5] 6
]
>> set2 = [4,1]
[
    [0] 4,
    [1] 1
]
>> set1.any?{ |num| set2.include?(num) }
true
>> set2 = [8,9]
[
    [0] 8,
    [1] 9
]
>> set1.any?{ |num| set2.include?(num) }
false

#9


1  

@kurumi has it right but I thought I'd add that I sometimes use this little extension when I only want a subset of an array (usually the hash keys though):

@kurumi说得对,但我觉得我应该补充一点,当我只想要一个数组的子集(通常是哈希键)时,我有时会使用这个小扩展:

class Hash
  # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3}
  def except(*keys)
    self.reject { |k,v|
      keys.include? k
    }
  end

  # Usage { :a => 1, :b => 2, :c => 3}.only(:a) -> {:a => 1}
  def only(*keys)
    self.dup.reject { |k,v|
      !keys.include? k
    }
  end
end

class Array
  def except(*values)
    self.reject { |v|
      values.include? v
    }
  end

  def only(*values)
    self.reject { |v|
      !values.include? v
    }
  end
end

#10


0  

Simple and best way :

简单而最好的方法:

([4,1] - [1,2,3,4,5,6]).empty? # => true

([4 1]-[1、2、3、4、5、6])空虚吗?# = >真

([4,1] - [4,1,6,2]).empty? # => true

([4 1]-[4 1 6,2])空虚吗?# = >真

([4,1] - [3,4,7]).empty? # => false

([4 1]-[3、4、7])空虚吗?# = >假

#11


0  

This will check whether an element exists in a array:

这将检查数组中是否存在元素:

students = ["jim", "bob", "sally"]
teachers = ["mrs. jones", "mrs. sharpe", "mrs. ray"]

puts "what's your name ?"
answer = gets.chomp

if answer.include?(students.to_s)
  puts "you are a student"

elsif
  puts "you are a teacher"

end