问题描述
|
如何根据内容将动态生成和排序的数组的内容打印到不同的文件中?
例如,假设我们有以下多维数组,该数组按第二列排序
[ [\'Steph\',\'Allen\',29],[\'Jon\',\'Doe\',30],[\'Jane\',[\'Tom\',\'Moore\',28] ]
目标是拥有3个文件:
last_name-Allen.txt <-包含Steph Allen 29
last_name-Doe.txt <-包含Jon Doe 30 Jane Doe 30
last_name-Moore.txt <-包含汤姆·摩尔28
解决方法
ar = [ [\'Steph\',\'Allen\',29],[\'Jon\',\'Doe\',30],[\'Jane\',[\'Tom\',\'Moore\',28] ]
grouped = ar.group_by{|el| el[1] }
# {\"Allen\"=>[[\"Steph\",\"Allen\",29]],\"Doe\"=>[[\"Jon\",\"Doe\",[\"Jane\",30]],\"Moore\"=>[[\"Tom\",\"Moore\",28]]}
grouped.each do |last_name,record|
File.open(\"last_name-#{last_name}.txt\",\'w\') do |f|
f.puts record.join(\' \')
end
end
, 如果要在Groovy中执行此操作,则可以使用groupBy
方法来获取基于姓氏的地图,如下所示:
// Start with your list
def list = [ [\'Steph\',28] ]
// Group it by the second element...
def grouped = list.groupBy { it[ 1 ] }
println grouped
版画
[Allen:[[Steph,Allen,Doe:[[Jon,Doe,[Jane,Moore:[[Tom,Moore,28]]]
然后,遍历此地图,为每个姓氏打开一个新文件并写入内容(在此示例中为制表符分隔)
grouped.each { surname,contents ->
new File( \"last_name-${surname}.txt\" ).withWriter { out ->
contents.each { person ->
out.writeLine( person.join( \'\\t\' ) )
}
}
}
, 在红宝石中:
array.each{|first,last,age| open(\"last_name-#{last}.txt\",\"a\"){|io| io.write([first,age,nil].join(\" \")}}
它在文件末尾添加了额外的空间。这是为了在要添加另一个实体时保留空间。
, 使用具有姓氏的哈希作为键,然后遍历哈希并将每个键/值对写入其自己的文件。
, 在Groovy中,您可以执行以下操作:
def a = [[\'Steph\',28]]
a.each {
def name = \"last_name-${it[1]}.txt\"
new File(name) << it.toString()
}
可能有更短(更简单)的方法来执行此操作。
, 您可以使用\“第二列\”作为键和值\\“文件句柄\”创建一个哈希值。如果您在哈希中获取密钥,则只需获取文件句柄并写入,否则创建新的文件句柄并插入哈希中。
, 这个答案在Ruby中:
# hash which opens appropriate file on first access
files = Hash.new { |surname| File.open(\"last_name-#{surname}.txt\",\"w\") }
list.each do |first,age|
files[last].puts [first,age].join(\" \")
end
# closes all the file handles
files.values.each(&:close)