1

我有航班路线代码的数据。它有很多这样的字符串:

routing = 'PBI-FLL/FMY/JAX/MIA/ORL-PNS/TPA-SRQ-CLE/CHI/HOU/WAS-DEN-ELP' 

我需要使用这样的字符串获取列表:

routinglist =  [['PBI'], ['FLL','FMY','JAX','MIA','ORL'], ['PNS','TPA'], ['SRQ'], ['CLE','CHI','HOU','WAS'], ['DEN']]

我写了这段代码,但它很复杂,不能按需要工作

routingrules = 'PBI-FLL/FMY/JAX/MIA/ORL-PNS/TPA-SRQ-CLE/CHI/HOU/WAS-DEN-ELP' 
airports = []   
nn = 0
few = ''
airportcount = 0

for simvol in routingrules:
    if (nn) % 4 == 0:
        previous = routingrules[nn:nn+3]
        if routingrules[nn+3:nn+4] == '/':
            few = few + previous + "1,2"

        elif routingrules[nn+3:nn+4] == '-':
            if few != '':
                airports.append([few + previous])
                airportcount = airportcount+1
                few = ''                
            else:
                airports.append([previous])
                airportcount = airportcount+1
        else:
            if few != '':
                airports.append([few + previous])
                airportcount = airportcount+1
                few = ''    

        nn = nn+1
    nn = nn+1 

print airports

它打印

[['PBI'], ['FLL1,2FMY1,2JAX1,2MIA1,2ORL'], ['PNS1,2TPA'], ['SRQ'], ['CLE1,2CHI1,2HOU1,2WAS'], ['DEN']]
4

2 回答 2

4

在 上拆分-,然后在每个组上/

[r.split('/') for r in routing.split('-')]

这输出:

>>> routing = 'PBI-FLL/FMY/JAX/MIA/ORL-PNS/TPA-SRQ-CLE/CHI/HOU/WAS-DEN-ELP' 
>>> [r.split('/') for r in routing.split('-')]
[['PBI'], ['FLL', 'FMY', 'JAX', 'MIA', 'ORL'], ['PNS', 'TPA'], ['SRQ'], ['CLE', 'CHI', 'HOU', 'WAS'], ['DEN'], ['ELP']]

与您的示例相比,这是最后一个额外的['ELP']条目,但我认为这是一个疏忽。再次删除它很容易。

于 2013-02-20T14:36:29.333 回答
1

尽管这个问题可能(是)矫枉过正,但pyparsing在这里效果很好。

routing = 'PBI-FLL/FMY/JAX/MIA/ORL-PNS/TPA-SRQ-CLE/CHI/HOU/WAS-DEN-ELP' 

from pyparsing import *
block   = Group(delimitedList(Word(alphas), '/'))
grammar = Group(delimitedList(block, '-'))

print grammar.parseString(routing)

印刷:

[[['PBI'], ['FLL', 'FMY', 'JAX', 'MIA', 'ORL'], ['PNS', 'TPA'], ['SRQ'], ['CLE', 'CHI', 'HOU', 'WAS'], ['DEN'], ['ELP']]]

当您想扩展语法时,这里的优势就来了。通常这些问题一开始很简单,随着时间的推移变得越来越复杂,在这里将语法与解析分开是很有用的。

于 2013-02-20T14:43:12.907 回答