Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To understand: From PHP Array to Python?

This is Common task In PHP and other programming languages.I moved from PHP developer. I want to make sure with this collections. Anyone have who good in python please help me to understand clearly . This is my collections from PHP code.

<?php
$php = array(1,2,3,4,5,6,7,8,9,10);
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i]."<br>";
?>

=>What is in Python?

<?php

for ($i = 0; $i < 10 ; $i ++)
echo $php[$i] = $i +1 ;
?>

=>What is in Python?

<?php
$php = array(1,2,3,4,5,6,7,8,9,10);
foreach ($php as $value)
echo $value."<br>";
?>

=>What is in Python?

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
?>

=>What is in Python?

<?php
$arr = array("mot"=>"one", "hai"=>"two","ba"=> "three");
foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}
?>

=>What is in Python?

<?php
$arr = array("one", "two","three");
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br />\n";
}
?>

=>What is in Python?

<?php
$arr = array("one", "two","three");
while ($element = each($arr)) {
    echo "Key: $element['key']; Value: $element['value']<br />\n";
}
?>

=>What is in Python?

<?php
$products = array( array("ITL","INTEL","HARD"),
                        array("MIR", "MICROSOFT","SOFT"),
                        array("Py4C", "pythonkhmer.wordpress.com","TUTORIAL")
                         );
for ($row = 0; $row < 3; $row++)
{
    for ($col = 0; $col <3; $col++)
        {
         echo "|".$products[$row][$col];
         }
echo "<br>";
}
?>

=>What is in Python?

like image 990
kn3l Avatar asked Nov 23 '09 07:11

kn3l


People also ask

What are the 3 types of PHP arrays?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

What is PHP array explain in detail with example?

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

What is the Python equivalent of an array?

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.


2 Answers

All of these are quite obvious really. I'm only listing the Pythonic ways to do these things. Update: Examples should now work in both Python 2 and Python 3. In Python 2 you could substitute xrange() for range() and iteritems() for items() for efficiency.

Example 1

PHP

$php = array(1,2,3,4,5,6,7,8,9,10);
for ($i = 0; $i < 10 ; $i ++)
echo $php[$i]."<br>";

Python (generally you iterate over lists in Python, instead of accessing by index):

lst = [1,2,3,4,5,6,7,8,9,10]
for item in lst:
    print(str(item) + "<br>")

Example 2

for ($i = 0; $i < 10 ; $i ++)
echo $php[$i] = $i +1 ;

Python:

lst = range(1, 11)
for item in lst:
    print(item)

Or maybe:

lst = []
for i in range(10):
    lst.append(i + 1)
    print(lst[-1])     # prints out last element

Example 3

$php = array(1,2,3,4,5,6,7,8,9,10);
foreach ($php as $value)
echo $value."<br>";

Same as 1st

Example 4

$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}

Python:

lst = [1, 2, 3, 4]
lst = [val * 2 for val in lst]

Example 5

$arr = array("mot"=>"one", "hai"=>"two","ba"=> "three");
foreach ($arr as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}

Python (note that {...} creates a dict [dictionary] in Python, not a list/):

dct = {'mot': 'one', 'hai': 'two', 'ba': 'three'}
for key, value in dct.items():
    print("Key: %s; Value: %s<br />" % (key, value))

Example 6

$arr = array("one", "two","three");
while (list($key, $value) = each($arr)) {
    echo "Key: $key; Value: $value<br />\n";
}

Python:

lst = ['one', 'two', 'three']
for key, value in enumerate(lst):
    print("Key: %d; Value: %s<br />" % (key, value))

Example 7

$arr = array("one", "two","three");
while ($element = each($arr)) {
    echo "Key: $element['key']; Value: $element['value']<br />\n";
}

There is no direct Python equivalent to this.

Example 8

$products = array( array("ITL","INTEL","HARD"),
                        array("MIR", "MICROSOFT","SOFT"),
                        array("Py4C", "pythonkhmer.wordpress.com","TUTORIAL")
                         );
for ($row = 0; $row < 3; $row++)
{
    for ($col = 0; $col <3; $col++)
    {
        echo "|".$products[$row][$col];
    }
    echo "<br>";
}

Python:

products = [['ITL', 'INTEL', 'HARD'],
    ['MIR', 'MICROSOFT', 'SOFT'],
    ['Py4C', 'pythonkhmer.wordpress.com', 'TUTORIAL']]

for product in products:
    for item in product:
        print('|' + item)
    print('<br>')

Or maybe a more Pythonic version:

for product in products:
    print('|%s<br>' % ('|'.join(product)))
like image 96
intgr Avatar answered Oct 18 '22 03:10

intgr


"What is in Python?", quite a philosophical question, always a great way to start a day. I think what is in Python can best be answered by the Zen of Python (type import this in an interactive shell):

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!

Sorry, couldnt resist. To answer the question you meant to ask, I direct you to the Python documentation, specifically the section about looping techniques as linked to by lutz.

Unless the syntax in the documentation manage to completely confuse you (though I doubt it) you will see how a loop is defined in Python. And once you have understood that, you will understand, by definition, how they differ (syntactically) from the loops youre used to in PHP.

Still not satisfied? Hmm... I guess you should read the tutorial again. Then, come back and ask specific questions that could yield specific answers. You wont find any silver bullets for a question this broad.

like image 39
Mizipzor Avatar answered Oct 18 '22 04:10

Mizipzor