如何排序数字字符串和文字字符串数组
问题描述:
你如何在Python和阵列Ruby中对列表进行排序,如:如何排序数字字符串和文字字符串数组
["car", "z", "9", "bus", "3"]
有此数组中的回报:
["bus", "car", "3", "z", "9"]
我我已经开始在Ruby中构建它,因为我知道它更好。我尝试.sort没有参数。 然后我开始写插入排序,希望我会重建它到我的订单,并写下这个方法。
def sort
@array.each do |value|
index = @array.index(value)
i = index - 1
while i >= 0
if value < @array[i]
@array[i + 1] = @array[i]
@array[i] = value
elsif (value =~ /\d/) == 0
# I wanted to do something here, whenever it stops at number to word comparison but didn't come up with anything workable
else
break
end
end
end
末
所有我能得到的是 [ “3”, “9”, “公交车”, “车”, “Z”] 但是,这是一个代码,挑战我必须完成和目标是按照字母顺序和数字顺序对字符串数组进行排序,并将数字字符串索引保留为原始数组,并将其按升序排列。我正在考虑为原始数组中的数字和单词的索引创建2个散列,并对这些值进行排序,然后将它们以正确的顺序注入到一个新数组中,但无法为其编写代码,仍然不确定这是否是最好的主意。
答
+0
好吧,意志混合了一下。 293是二百九十一,它是[“two”,“hundred”,“ninty”,“three”]。sort == [“hundred”,“ninty”,“three”,“two”]我需要的结果。 – 2014-11-06 17:15:24
答
所以这里是我如何解决它。感谢Mark Thomas提供分区和插入方法的提示。请评论您对代码效率和清晰度的想法和建议。
def sort
# storing indicies of number strings to map them back later
num_indicies = @array.map {|i| @array.index(i) if (i =~ /\d/) == 0}.compact
# if there are no numbers
if num_indicies.empty?
@array.sort!
#if there are only numbers
elsif num_indicies.length == @array.length
@array = @array.map {|n| n.to_i}.sort
else
# separating numbers and words for proper sort
separation = @array.partition {|c| (c =~ /\d/) == 0}
# sorting first array. Converting to integer in order to sort numbers bigger than 10
separation[0] = separation[0].map {|n| n.to_i}.sort
# sorting array of words and letters
separation[1].sort!
# inserting numbers in their original spots
index = 0
separation[0].each do |num|
#inserting sorted integers inside of array of sorted strings, simultaniously converting them into strings
@array = separation[1].insert(num_indicies[index], num.to_s)
# switching index for another iteration
index += 1
end
end
end
首先,选择一种语言。其次,解释你为什么认为这应该是输出。第三,展示你到目前为止所尝试的内容,并描述它到底有什么问题。 – jonrsharpe 2014-11-05 11:52:07
最重要的是,解释为什么你认为''3“'应该在''z''之前排序,但是后面跟着''9”'。我在这里看不到合理的进展。 – 2014-11-05 11:54:23
对不起,开始不好,对我来说是清晨。刚编辑它。 – 2014-11-05 14:53:11