Sunday, May 30, 2010

perl vs python (hash and list/array)











  perl python
  hash array hash array (tuple for constant, and
list for variable)
symbol
(whole, ele)
{},{} (),[] {},[] []/()
(list/tuple), []
declare my %hash =
("foo", 35)

my %last_name = (

       
"fred" => "flintstone",

…)
my @var = (11, 27.1 , "a string");

my @var = qw/ hello my god /
some_dict =
{

       
"fred": "flintstone",

…}
list = ['milk',
1, 'lettuce']
clear %hash = () @var = ()

$#array = -1;
dict={} list = []
retain
the size
my $count = keys %hash; $scalar = @array;

$scalar = scalar @array;
count = len(hash) l=len(L)
add/use
element
$last_name{'wilma'} =
"flintstone";
$array[3] = 5

@list2 = (1, @list1, 5); 
#nesting is not supported

@subarray2 = @array[0,1..3]
some_dict['wilma'] =
"flintstone"
a = (1, 2); b = (3, 4); c = (a, b) => ((1,2),(3,4))

c=a+b => (1,2,3,4)

L[i:j] = J;
use
keys/values
my @k =
keys %hash;

my @v = values %hash;

while ( ($key, $value) = each %hash )

 
  k =
hash.keys()

v = hash.values()

for (key, value) in hash.items():

  ...
 
check
existence of an ele
if (exists $books{'dino'}) exists  $array[
$index ] -> existence

defined $array[ $index ] -> defined
if books.has_key('dino'):  
add an
ele to the end
  push(@coins,
"Penny");
  list.append(x)
add an
ele to the beginning
  shift(@coins,
"First");
  list.insert(0,
x)
remove
an ele
delete $books{$person};    del books[person]  
from the
beginning
  $var=unshift(@coins);   a=list.pop([i])
from the
end
  $var=pop(@coins);   a=list.pop()
sort sort { $a <=> $b }
keys(%hash)
@array2 =
reverse sort (@array);
  sorted([5, 2, 3, 1, 4])

list.sort()

list.reverse()
sort
(unique value)
  my @s = uniq sort @a;    
join/split   $firststring
= join(", ",@array);

@array = split('-',$astring);
   
index       list.index(var)  #find the first ele that match var
ref my
$hash_ref = {};

$href->{ $key } = $value;
    ref_list=true_list





No comments: