2011-03-21 90 views
0

這是第一次不是python => php但是php => python。 我在Python中遇到了一些小數組問題。 (我已經去過到docs.python.org)數組幫助:將​​php代碼轉換爲python

這裏是我的問題: 我得到的字符串蟒蛇夫婦這樣的:

(People 1): 
    <criteria a> <data of the criteria> 
    <criteria b> <data of the criteria> 
    <criteria c> <data of the criteria> 
    <criteria d> <data of the criteria> 
(People 2): 
    <criteria a> <data of the criteria> 
    <criteria b> <data of the criteria> 
    <criteria d> <data of the criteria> 
... 

(注人2個標準C不存在) 所以我想這樣做(在PHP它很容易):

array_push(tab[ "criteria a" ], 
    array("People1", "data of the criteria") 
); 

然後我想表明,存在規定 - 所有的列表,並使用數組來創建一個漂亮的「插入SQL查詢「爲我的數據庫。

任何想法如何做到這一點? 我應該在哪裏看? 我想念字符串索引數組....

+1

你沒完成你的問題 – vartec 2011-03-21 13:30:13

+0

比較容易回答,如果你真的問一個問題...;) – Nico 2011-03-21 13:30:28

+2

Python已經字典,如果你需要字符串索引 – lunixbochs 2011-03-21 13:36:09

回答

3

在Python中,你有「字典」而不是「字符串索引數組」。 它們的語法與數組不同。

你可以做

data = {} 
data["people 1"] = {} 
data["people 1"]["criteria a"] = "bla" 
data["people 1"]["criteria b"] = "ble" 
data["people 2"] = {} 

...

您可以檢索使用值方法的字典值的所有內容:

>>> print data["people 1"].values() 
["ble", "bla"] 

(注意順序是任意的,當你做到這一點) 無論如何,你最好檢查Python基本數據結構的文檔來做到這一點: http://docs.python.org/tutorial/datastructures.html

+0

非常感謝你,這就是我需要開始 – 2011-03-21 14:07:14

0

好吧,這是矯枉過正,但你會發現很有趣;-)

import collections 
import re 

def makeMatcher(regex): 
    reg = re.compile(regex).match 
    def matcher(s): 
     match = reg(s) 
     return match and match.groups() # return None or tuple of match-values 
    return matcher 

class StatefulIter(collections.Iterator): 
    def __init__(self, seq, stateVars, *transitions, **kwargs): 
     """ 
     StatefulIter crunches input sequence using transition rules 

     :seq   :input sequence of data to operate on 
     :stateVars  :state variables to operate on - dict OR space-separated string OR collection of strings 
     :*transitions :list of (isMatch, onMatch) tuples 
          (isMatch can be a function or a regex string) 
          isMatch(data) returns matched fields or None 
          onMatch(statedict, *fields) processes matched fields, returns isOutput 
     :**outfn  :if isOutput, return outfn(statedict) 

     """ 
     outfn = kwargs.pop('outfn') 
     super(StatefulIter,self).__init__(**kwargs) 
     self.seq = seq 
     if isinstance(stateVars, dict): 
      self.statedict = stateVars 
     else: 
      if isinstance(stateVars, basestring): 
       stateVars = stateVars.split() 
      self.statedict = {s:None for s in stateVars} 
     self.trans = [(isMatch if callable(isMatch) else makeMatcher(isMatch), onMatch) for isMatch,onMatch in transitions] 
     self.outfn = outfn 

    def next(self): 
     _sd = self.statedict 
     while True: 
      data = self.seq.next() 
      for isMatch,onMatch in self.trans: 
       match = isMatch(data) 
       if match is not None: 
        res = onMatch(_sd,*match) 
        if res: 
         return self.outfn(_sd) 
        else: 
         break 

class CriteriaIter(StatefulIter): 
    states = 'person criteria date' 

    isPeople = r'\((.+)\):' 
    @staticmethod 
    def onPeople(statedict, pers): 
     statedict['person'] = pers 
     return False 

    isCriteria = r'\s*<(.*?)>\s*<(.*?)>' 
    @staticmethod 
    def onCriteria(statedict, crit, date): 
     statedict['criteria'] = crit 
     statedict['date']  = date 
     return True 

    @staticmethod 
    def outfn(statedict): 
     return statedict['person'], statedict['criteria'], statedict['date'] 

    def __init__(self, seq, outfn=None): 
     people = (CriteriaIter.isPeople, CriteriaIter.onPeople) 
     criteria = (CriteriaIter.isCriteria, CriteriaIter.onCriteria) 
     outfn = outfn or CriteriaIter.outfn 
     super(CriteriaIter,self).__init__(seq, CriteriaIter.states, people, criteria, outfn=outfn) 

class CriteriaFile(file): 
    def __iter__(self): 
     return CriteriaIter(self) 

def main(): 
    with CriteriaFile('data.txt') as inf: 
     allEntries = [entry for entry in inf] 
    allCriteria = set(entry[1] for entry in allEntries) 

if __name__=="__main__": 
    main()