帮助数组:将PHP代码转换为python

时间:2011-03-21 13:28:27

标签: php python

这是第一次不是python => php但php =>蟒蛇。 我在python中的数组有小问题。 (我已去过docs.python.org)

这是我的问题: 我得到了像这样的字符串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查询”。

知道怎么做吗? 我应该在哪里看? 我错过了字符串索引数组....

2 个答案:

答案 0 :(得分:3)

在Python中,您有“词典”而不是“字符串索引数组”。 它们的语法与数组不同。

你可以做到

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

...

您可以使用values方法检索词典值的所有内容:

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

(请注意,执行此操作时,顺序是任意的) 无论如何,你最好检查Python基本数据结构的文档来做到这一点: http://docs.python.org/tutorial/datastructures.html

答案 1 :(得分: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()