理解:从 PHP 数组到 Python?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1781617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:02:55  来源:igfitidea点击:

To understand: From PHP Array to Python?

phppythonarraysloops

提问by kn3l

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 开发人员移居。我想确定这个系列。任何擅长python的人请帮助我理解清楚。这是我从 PHP 代码中收集的集合。

<?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?

=>Python 中有什么?

<?php

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

=>What is in Python?

=>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?

=>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?

=>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?

=>Python 中有什么?

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

=>What is in Python?

=>Python 中有什么?

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

=>What is in Python?

=>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?

=>Python 中有什么?

回答by intgr

All of these are quite obvious really. I'm only listing the Pythonicways 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.

所有这些都非常明显。我只是列出了做这些事情的Pythonic方法。更新:示例现在应该适用于 Python 2 和 Python 3。在 Python 2 中,您可以用 xrange() 代替 range(),用 iteritems() 代替 items() 以提高效率。

Example 1

示例 1

PHP

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 iterateover lists in Python, instead of accessing by index):

Python(通常您在 Python 中遍历列表,而不是通过索引访问):

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

Example 2

示例 2

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

Python:

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

示例 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

示例 4

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

Python:

Python:

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

Example 5

例 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/):

Python(请注意,在 Python中{...}创建了一个dict[dictionary],而不是一个列表/):

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

Example 6

例 6

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

Python:

Python:

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

Example 7

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

没有与此等效的直接 Python。

Example 8

例 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:

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:

或者也许是一个更 Pythonic 的版本:

for product in products:
    print('|%s<br>' % ('|'.join(product)))

回答by Mizipzor

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

“Python 中有什么?”,这是一个非常哲学的问题,总是一个很好的开始一天的方式。我认为是在Python可以最好的Python的禅(类型回答import this在一个交互的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 rightnow.
  • 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 techniquesas linked to by lutz.

对不起,忍不住了。为了回答您想问的问题,我将您引导至Python 文档,特别是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.

除非文档中的语法使您完全困惑(尽管我对此表示怀疑),否则您将看到 Python 中如何定义循环。一旦你理解了这一点,你就会明白,根据定义,它们与你在 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.

还是不满意?嗯...我想你应该再读一遍教程。然后,回来提出可以产生特定答案的特定问题。对于如此广泛的问题,您找不到任何灵丹妙药。

回答by Mizipzor

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

您可以在Python 教程 中阅读循环介绍。

回答by ercan

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

这个问题让我想起了一位智者说的:“给一个人一条鱼,你养活了他今天。教一个人钓鱼,你养活了他一生……”