In case of for loop in PHP i wrote
foreach($vertex['neighbours'] as $n_vertex)
Is it similar to the for loop below in Python
for n_vertex in vertex['neighbors']:
Similarly in case of While loop in PHP i used
while(!empty($my_queue))
Is it similar to the while loop below in Python
while my_queue:
If not, what is correct version of for and while loop in Python following the one in PHP.
Yes, these are similar.
They're not exactly identical, but the differences won't matter in most code.*
And using my_queue
directly as a test, rather than an empty
method/function, is the Pythonic way to do it, as recommended in PEP 8 :
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
So, you've done everything exactly right.
Of course in some cases, using a list comprehension or generator expression (which have no direct analogy in PHP) may be more concise or readable than a for
statement, but you never need to use them.
* First, a Python for
loop creates an iterator from the source, then calls next(it)
over and over until StopIteration
is raised, which is pretty different from what happens under the covers in PHP. Unless you're using very weird types, or trying to mutating the object you're iterating over during iteration, you'll never notice the difference. Second, in Python, unlike PHP, my_queue
could theoretically be something which is an iterable, but not a sequence, like an iterator—in which case while my_queue:
will not work. That's unlikely for something you've named my_queue
, however.
Both of your for loops are fine. They are same/similar. But the while loops are different from one another:
while(!empty($my_queue))
is checking the list not empty and going through it. On the other hand,
while my_queue:
will not be working if my_queue is not a boolean value. Hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.