views:

238

answers:

4

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?

+3  A: 

You can read an introduction to loops in the Python tutorial.

Thanks Lutz .If you can give me a corresponding code (php->python).what I post here it would be great.
python
Did you read the Python tutorial?
I am quick learn.i am switch from php to python for a while.thanks.
python
If you are learning quickly, you should be able to answer your question on your own after reading the Python tutorial.
In fact.I am reading now.when u sent to me ,thanks.but at here people are motivate to share quickly,when I am in reading your link.other people make uderstand very quick..Thanks Lutz alotsss
python
+8  A: 

All of these are quite obvious really. I'm only listing the Pythonic ways to do these things

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 xrange(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.iteritems():
    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>'
intgr
If the first example really iterates over integers str(item) needs be used when printing those values.
paprika
Many thanks @ intgr :)
python
this shows clearly how python syntax is less verbose and more clear that php IMHO
jujule
This want I am looking for...Thankssssssssssssssss
python
I see python easy to learn than other languages.
python
@paprika: Thanks, fixed it :)
intgr
One important difference between associative arrays in PHP and dicts in Python is that the order of an associative array in PHP is just as you set it whereas with Python's dicts their order is arbitrary, or rather, they are simply unordered. This along with PHP's totally awesome documentation is all I miss from PHP. Otherwise I'm a happy Python newbie.
donut
I would have liked seeing xrange somewhere, for example in ex. 2. for item in xrange(1,10): . That looks even a bit more clean.
extraneon
@extraneon: I added another Python version to 'example 2'. You're right, the previous code probably didn't do it quite the way the asker expected.
intgr
@intgr thank you alot.
python
+6  A: 

"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.

mizipzor
Thanks you very much.thank you all of you.I always welcome...:)
python
+1: "Then, come back and ask specific questions that could yield specific answers." This is really the issue with this question. It seems the author didn't realize that this is a broad topic about how looping and data structures work in Python, and not a specific problem.
paprika
+1  A: 

This question reminds me of a wise man who had said, "Give a man a fish; you have fed him for today. Teach a man to fish; and you have fed him for a lifetime..."

ercan
I think this quote is not relevant to this question. Having comparable examples is a good tool for learning. That's all these are -- examples -- the asker didn't want us to solve his problems for him.
intgr