解压缩数据名称的最简单方法是什么?
例如,更改压缩格式:
abc[3:0]
解压缩形式:
abc[3]
abc[2]
abc[1]
abc[0]
优选1个衬垫:)
答案 0 :(得分:2)
Perl:
#!perl -w
use strict;
use 5.010;
my @abc = qw/ a b c d /;
say join( " ", reverse @abc[0..3] );
或者如果您希望它们成为单独的变量:
my( $abc3, $abc2, $abc1, $abc0 ) = reverse @abc[0..3];
修改:根据您的澄清:
my $str = "abc[3:0]";
$str =~ /(abc)\[(\d+):(\d+)\]/;
my $base = $1;
my $from = ( $2 < $3 ? $2 : $3 );
my $to = ( $2 > $3 ? $2 : $3 );
my @strs;
foreach my $num ( $from .. $to ) {
push @strs, $base . '[' . $num . ']';
}
答案 1 :(得分:1)
这是我过去做过的一个小小的pyparsing练习,适合你的例子(也支持多个范围和不成对的索引,所有索引都用逗号分隔 - 参见最后一个测试用例):
from pyparsing import (Suppress, Word, alphas, alphanums, nums, delimitedList,
Combine, Optional, Group)
LBRACK,RBRACK,COLON = map(Suppress,"[]:")
ident = Word(alphas+"_", alphanums+"_")
integer = Combine(Optional('-') + Word(nums))
integer.setParseAction(lambda t : int(t[0]))
intrange = Group(integer + COLON + integer)
rangedIdent = ident("name") + LBRACK + delimitedList(intrange|integer)("indexes") + RBRACK
def expandIndexes(t):
ret = []
for ind in t.indexes:
if isinstance(ind,int):
ret.append("%s[%d]" % (t.name, ind))
else:
offset = (-1,1)[ind[0] < ind[1]]
ret.extend(
"%s[%d]" % (t.name, i) for i in range(ind[0],ind[1]+offset,offset)
)
return ret
rangedIdent.setParseAction(expandIndexes)
print rangedIdent.parseString("abc[0:3]")
print rangedIdent.parseString("abc[3:0]")
print rangedIdent.parseString("abc[0:3,7,14:16,24:20]")
打印:
['abc[0]', 'abc[1]', 'abc[2]', 'abc[3]']
['abc[3]', 'abc[2]', 'abc[1]', 'abc[0]']
['abc[0]', 'abc[1]', 'abc[2]', 'abc[3]', 'abc[7]', 'abc[14]', 'abc[15]', 'abc[16]', 'abc[24]', 'abc[23]', 'abc[22]', 'abc[21]', 'abc[20]']