我有一个如下所示的数组:
booklist = [000A,000B,000C]
我想成对组合所有元素,以便这是输出数组:
combinedbooks = [000A|000B, 000A|000C, 000B|000C]
我所做的是以下内容:
combinedbooks= Array.new
for i in 0..booklist.length
for j in i+1..booklist.length
combinedbooks.push(booklist(i) + "|" + booklist(j))
end
end
它不起作用,我不知道为什么
答案 0 :(得分:4)
嵌套for循环的替代方法是使用#combination
:
[25] pry(main)> booklist
=> ["000A", "000B", "000C"]
[26] pry(main)> booklist.combination(2).map { |i| i.join("|") }
=> ["000A|000B", "000A|000C", "000B|000C"]
答案 1 :(得分:3)
您的代码实际上存在两个问题。第一个是数组的特定元素应该用括号[]
引用,而不是括号()
。第二个是,由于Ruby中的数组是零索引的,list[list.length]
不存在(list[list.length-1]
是数组中的最后一个元素)。如果我们解决了这两个问题,你最终得到:
booklist = ["000A", "000B", "000C"]
combinedbooks = Array.new
for i in 0..booklist.length-1
for j in i+1..booklist.length-1
combinedbooks.push(booklist[i] + "|" + booklist[j])
end
end
哪个有效。
Ruby是一种非常强大的语言,所以实际上有一种更简单的方法可以使用combination
,map
和join
方法组合Array
,{{3}}和{{3}}方法。 3}}:
booklist = ["000A", "000B", "000C"]
combinedbooks = booklist.combination(2).map{|combination| combination.join("|")}
答案 2 :(得分:0)
booklist = ['000A', '000B', '000C']
joined_booklist = []
booklist.each_with_index do |book, i|
next if i == (booklist.length - 1)
((i+1)..(booklist.length-1)).each do |j|
joined_booklist << book + "|" + booklist[j]
end
end
答案 3 :(得分:0)
这是另一个until loop
booklist = ["000A","000B","000C"]
# duplicate the array
booklist_dup = booklist
result_array = []
until booklist_dup.empty?
# takes the first element out of the array
first_el = booklist_dup.shift
# create a combination with each element of the remaining array
booklist.each{ |el| result_array << first_el + "|" + el}
end
# => ["000A|000B", "000A|000C", "000B|000C"]
答案 4 :(得分:0)
对这种行为使用Array#组合:
booklist = ['000A', '000B', '000C']
booklist.combination(2).map { |pair| pair.join('|') }
答案 5 :(得分:0)
你可以尝试这样的事情。
booklist = ['000A', '000B', '000C']
pairs = booklist.combination(2).to_a
pairs.map!{|a,b|"#{a}|#{b}"}