标题: [数值计算] 批处理怎样取出一组变量中数值最大和最小的变量名? [打印本页]
作者: chouxia 时间: 2019-3-6 10:56 标题: 批处理怎样取出一组变量中数值最大和最小的变量名?
set num0=0&set num1=0&set num4=0&set num6=0&set num8=0&set num10=0&set num12=0
变量赋值
现在需要比较变量值的大小,取出最大和最小的变量名。(如果数值一致,输出【num数字】中数字最大和最小的那个)
哪位高人给段代码。谢谢
作者: ivor 时间: 2019-3-6 14:00
笨方法- @echo off & setlocal ENABLEDELAYEDEXPANSION
- rem 初始化
- set num0=%random%&set num1=%random%&set num4=%random%&set num6=%random%&set num8=%random%&set num10=%random%&set num12=%random%
- set maxValue=%num0% &set minValue=%num0%
-
- for /f "tokens=1,2 delims==" %%a in ('set num ^| findstr "num[0-9]"') do (
- echo %%b
- if %%b gtr !maxValue! set maxValue=%%b
- if %%b lss !minValue! set minValue=%%b
- )
- echo 最小值:%minValue%最大值:%maxValue%
- pause
复制代码
作者: chouxia 时间: 2019-3-6 14:29
回复 2# ivor
set num ^| findstr "num[0-9]"
这行代码没理解。
能解释下吗
作者: 523066680 时间: 2019-3-6 14:45
改自二楼代码,增加值相同时对变量名的排序。- @echo off & setlocal ENABLEDELAYEDEXPANSION
- set mask=##########
- set num0=1&set num1=5&set num4=0&set num6=0&set num8=0&set num10=1&set num12=5&set num13=1
- set maxValue=%num0% &set minValue=%num0%
-
- rem sort value first
- for /f "tokens=1,2 delims=num=" %%a in ('set num ^| findstr "num[0-9]"') do (
- set foo=!mask!%%a
- set bar=!mask!%%b
- set order_!bar:~-10!_!foo:~-10!=1
- )
-
- rem %%a = value, %%b = itemNO.
- for /f "tokens=1,2 delims=order=_" %%a in ('set order') do (
- if defined min (set max=%%b) else (set min=%%b)
- )
-
- echo the minimal item: num%min:#=%, value = !num%min:#=%!
- echo the maximum item: num%max:#=%, value = !num%max:#=%!
复制代码
- the minimal item: num4, value = 0
- the maximum item: num12, value = 5
复制代码
作者: 523066680 时间: 2019-3-6 15:14
非批,语法糖- my %hash = (0=>1, 1=>5, 4=>0, 6=>0, 8=>0, 10=>1, 12=>5, 13=>1);
- my @idx = sort { $hash{$a} <=> $hash{$b} || $a <=> $b } ( keys %hash );
- grep { printf "hash[%2d] = %d\n", $_, $hash{$_} } @idx;
复制代码
- hash[ 4] = 0
- hash[ 6] = 0
- hash[ 8] = 0
- hash[ 0] = 1
- hash[10] = 1
- hash[13] = 1
- hash[ 1] = 5
- hash[12] = 5
复制代码
作者: xczxczxcz 时间: 2019-3-6 15:48
没有写PS 不科学。补一个:- $VARIABLE = @(
- [PSCustomObject] @{ NAME = 'VAR1'; NUM= 1 }
- [PSCustomObject] @{ NAME = 'VAR2'; NUM= 2 }
- [PSCustomObject] @{ NAME = 'VAR3'; NUM= 20 }
- [PSCustomObject] @{ NAME = 'VAR7'; NUM= 20 }
- [PSCustomObject] @{ NAME = 'VAR8'; NUM= 20 }
- [PSCustomObject] @{ NAME = 'VAR10'; NUM= 23 }
- [PSCustomObject] @{ NAME = 'VAR9'; NUM= 20 }
- [PSCustomObject] @{ NAME = 'VAR4'; NUM= 12 }
- [PSCustomObject] @{ NAME = 'VAR5'; NUM= 23 }
- [PSCustomObject] @{ NAME = 'VAR6'; NUM= 12 }
- );
- $MIN_NAME = ( $VARIABLE | sort NUM | select -first 1 ).NAME;
- $MIN_VALUE = ( $VARIABLE | sort NUM | select -first 1 ).NUM;
- $MAX_NAME = ( $VARIABLE | sort NUM | select -LAST 1 ).NAME;
- $MAX_VALUE = ( $VARIABLE | sort NUM | select -LAST 1 ).NUM;
- "最大值:{0:0}={1:0}; 最小值:{2:0}={3:0}" -f $MAX_NAME,$MAX_VALUE,$MIN_NAME,$MIN_VALUE;
复制代码
欢迎光临 批处理之家 (http://www.bathome.net/) |
Powered by Discuz! 7.2 |