gpt4 book ai didi

PHP 与 Python 代码差异 - 数组、Foreach 循环

转载 作者:行者123 更新时间:2023-12-01 05:54:25 26 4
gpt4 key购买 nike

我希望这个问题的措辞符合本网站的政策。

我正在尝试将一段Python代码转换为PHP代码。我已经翻译了几乎所有函数,除了我无法弄清楚 PHP 与 Python 中的数组和 Foreach 循环有何不同。

qstid = dbinputsurveyid+'X'+str(question.gid)+'X'+str(question.qid)
index=columns.index(qstid)
for i,a in enumerate(data[index]):
if a!=None and a!='':
answer=int(data[index][i])
answerCodes=list(answersCode[question.qid])
answerindex = answerCodes.index(str(answer))
answerorder = answersOrder[question.qid][a]
addAnswers(db, data[0][i], question.sid, question.gid, question.qid, question.type, answers[question.qid][answerindex], None,answerorder, None, None,None)

来 self 读过的一些书。我认为 python 中的 enumerate 相当于 PHP 中的 foreach 循环。但我不确定“i”和“a”如何在上面的代码中发挥作用。它们的定义似乎不像 PHP 中那样。感谢任何帮助或见解。

最佳答案

该循环中的符号 i, a 使您可以访问列表的索引和值。

来自 Python docs :

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

所以,在 Python 中你会:

for i,a in enumerate( ['some', 'list'])

这相当于 PHP:

$array = ['some', 'array']; 
// Or, for PHP < 5.4: $array = array( 'some', 'array');
foreach( $array as $i => $a)

关于PHP 与 Python 代码差异 - 数组、Foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13182195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com