[英]Stuck on PHP to Python Translation
我正在尝试将一些PHP代码翻译成Python,并且我在以下代码(包含在上下文中)的第4行中停留:
$table = array();
for ($i = 0; $i < strlen($text); $i++) {
$char = substr($text, $i, $look_forward);
if (!isset($table[$char])) $table[$char] = array();
}
如果使用array()
在PHP中创建数组,那么$table[$char] = array()
在做什么? 在现有数组中创建一个新数组? 还是扩展阵列?
这是完成了什么? 什么是Python相当于此?
if (!isset($table[$char])) $table[$char] = array();
在我看来,你应该使用另一个数据结构而不是list
作为table
变量。 我认为dict
对于这个目的应该是好的。
我刚刚尝试用Python模拟你的PHP代码:
table = {} # use dictionary instead of list here
for char in text:
if char not in table:
table[char] = []
# do your stuff with table[char]
pass
另外,我建议您查看https://docs.python.org/3/library/collections.html#collections.defaultdict
使用该类,可以通过以下方式重写代码:
import collections
table = collections.defaultdict(list)
for char in text:
# do your stuff with table[char], empty list is created by default
pass
if(!isset($ table [$ char]))$ table [$ char] = array(); 如果$ table [$ char]尚未设置,则将$ table [$ char]变量的值设置为array()
$ table是空数组,因此它不包含“ $ char ”作为键,因此它检查是否设置了$ table [$ char] ,如果没有,则将其($ table [$ char])值设置为array() 。
如果你把你的代码
$table = array();
for ($i = 0; $i < strlen($text); $i++) {
$char = substr($text, $i, $look_forward);
$table[$char] = array();
}
然后它发出通知,如通知: 未定义的索引:$ char in
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.