在每个元素中找到的第一个数字上对数组进行排序 [英] sorting an array on the first number found in each element

查看:138
本文介绍了在每个元素中找到的第一个数字上对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找对数组进行排序的帮助,其中每个元素都由数字,然后是字符串,然后是数字"组成.我想对数组元素的第一个数字部分进行排序,然后降序排列(以便我首先列出较高的数字),同时还要列出文本等.

I'm looking for help sorting an array where each element is made up of "a number, then a string, then a number". I would like to sort on the first number part of the array elements, descending (so that I list the higher numbers first), while also listing the text etc.

我仍然是初学者,因此也欢迎以下替代方案

am still a beginner so alternatives to the below are also welcome

use strict;
use warnings;

my @arr = map {int( rand(49) + 1) } ( 1..100 ); # build an array of 100 random numbers between 1 and 49

my @count2;

foreach my $i (1..49) {

    my @count = join(',', @arr) =~ m/$i,/g; # maybe try to make a string only once then search trough it... ???
my $count1 = scalar(@count); # I want this $count1 to be the number of times each of the numbers($i) was found within the string/array.

    push(@count2, $count1 ." times for ". $i); # pushing a "number then text and a number / scalar, string, scalar" to an array.
}

#for (@count2) {print "$_\n";}
# try to add up all numbers in the first coloum to make sure they == 100

 #sort @count2 and print the top 7
@count2 = sort {$b <=> $a} @count2; # try to stop printout of this, or sort on =~ m/^anumber/ ??? or just on the first one or two \d

foreach my $i (0..6) {
 print $count2[$i] ."\n"; # seems to be sorted right anyway
}

推荐答案

首先,将数据存储在数组中,而不是字符串中:

First, store your data in an array, not in a string:

# inside the first loop, replace your line with the push() with this one:
push(@count2, [$count1, $i]; 

然后,您可以轻松地按每个子数组的第一个元素进行排序:

Then you can easily sort by the first element of each subarray:

my @sorted = sort { $b->[0] <=> $a->[0] } @count2;

然后在打印时,构造字符串:

And when you print it, construct the string:

printf "%d times for %d\n", $sorted[$i][0], $sorted[$i][1];

另请参见: http://perldoc.perl.org/perlreftut.html perlfaq4

这篇关于在每个元素中找到的第一个数字上对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆