what is the easiest way to decompress a data name? for exmaple change compressed form: abc[3:0] into decompressed form: abc[3] abc[2] abc[1] abc[0]
preferable 1 liner :)
what is the easiest way to decompress a data name? for exmaple change compressed form: abc[3:0] into decompressed form: abc[3] abc[2] abc[1] abc[0]
preferable 1 liner :)
In python:
>>> abc = [1,2,3]
>>> a, b, c = abc
>>> a
1
>>> b
2
>>> c
3
You can unpack elements of a list or tuple into variables.
Note that you must use the same number of variables as the number of elements.
For instance:
>>> abcd = [1,2,3,4]
>>> a, b, c = abcd
would raise ValueError: too many values to unpack
, just as:
>>> abc = [1,2,3]
>>> a, b, c, d = abc
would raise ValueError: need more than 4 values to unpack
In Perl:
#!perl -w
use strict;
use 5.010;
my @abc = qw/ a b c d /;
say join( " ", reverse @abc[0..3] );
Or if you wanted them into separate variables:
my( $abc3, $abc2, $abc1, $abc0 ) = reverse @abc[0..3];
Edit: Per your clarification:
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 . ']';
}
This is a little pyparsing exercise that I've done in the past, adapted to your example (also supports multiple ranges and unpaired indexes, all separated by commas - see the last test case):
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]")
Prints:
['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]']