2016-05-05 21 views
1

Ich versuche, einige PHP-Code zu Python zu übersetzen und ich bin auf der 4. Zeile im folgenden Code (im Lieferumfang für Kontext) fest:Steckt PHP zu Python Übersetzung

$table = array(); 
for ($i = 0; $i < strlen($text); $i++) { 
    $char = substr($text, $i, $look_forward); 
    if (!isset($table[$char])) $table[$char] = array(); 
} 

Wenn array() verwendet wird um ein Array in PHP zu erstellen, was macht $table[$char] = array()? Erstellen eines neuen Arrays in einem vorhandenen Array? Oder erweitert es das Array?

Was bewirkt das? Was wäre das Python-Äquivalent dazu?

if (!isset($table[$char])) $table[$char] = array();

Antwort

-1

if (isset ($ table [$ char])!) $ Table [$ char] = array(); setzt Wert von $ table [$ char] Variable als Array() wenn $ table [$ char] noch nicht

$ gesetzt ist Tabelle leer Array ist, so dass es nicht enthalten "hat $ char "als Schlüssel, so dass ihre Überprüfung, ob $ table [$ char] gesetzt ist oder nicht, wenn nicht, dann gesetzt seinen ($ table [$ char]) Wert als Array().

, wenn Sie Ihren Code zu setzen wie

$table = array(); 
for ($i = 0; $i < strlen($text); $i++) { 
    $char = substr($text, $i, $look_forward); 
    $table[$char] = array(); 
} 

dann gibt es Vermerk Hinweis: Undefined index: $ char in

1

mir scheint, sollten Sie eine andere Datenstruktur als list als table verwenden Variable. Ich nehme an, dass dict für den Zweck nett sein sollte.

Ich habe nur einen schnellen Versuch gemacht PHP-Code in Python zu imitieren:

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 

Auch ich schlage vor, Sie schauen in https://docs.python.org/3/library/collections.html#collections.defaultdict

Mit der Klasse der Code im folgenden neu geschrieben werden könnte Weg:

import collections 

table = collections.defaultdict(list) 
for char in text: 
    # do your stuff with table[char], empty list is created by default 
    pass