在列表中的“无”表示的边界内工作

时间:2011-08-12 00:33:57

标签: python

我有一个输入列表,例如:

mylist = [('a', [(2, 4), (0, 5)]), ('b', [(3, 9), (1, 1)]), ("'", None), ('c', [(1,7), (2, 8)])] 

我必须在列表中的值之间进行比较。像(2,4)这样的项表示范围。列表中的“无”条目就像边界。比较发生在边界内。所以在这里,比较将首先在a和b之间。比较基本上是在不同条件下给出的值之间,例如它们是否重叠,因为它们是范围。因此,在与邻居的范围进行比较后,范围会发生变化。

if within the boundary : (something like "if ! None : then continue")
    do the comparisons between the items inside the boundary 
if None :
    move to next boundary
    do the comparisons between the items inside the next boundary   

比较是用简单的规则,例如比较(2,4)和(3,9)然后这两个部分重叠,因此选择它们之间的共同点。因此,结果是(3,4)。

我已经编写了所有比较规则的代码,但我尝试了它们没有边界。但它们应该在界限内。我无法在代码中表达界限。谢谢。

2 个答案:

答案 0 :(得分:2)

您可以使用None测试他们的第二个值是否为itertools.groupby来对项目进行分组。

>>> import itertools
>>> mylist
[('a', [(2, 4), (0, 5)]), ('b', [(3, 9), (1, 1)]), ("'", None), ('c', [(1, 7), (2, 8)])]
>>> grp = itertools.groupby(mylist, lambda i: i[1] is None)
>>> res = [tuple(i[1]) for i in grp if not i[0]] #use parantheses for faster generator expression.
>>> pprint.pprint(res)
[(('a', [(2, 4), (0, 5)]), ('b', [(3, 9), (1, 1)])),
 (('c', [(1, 7), (2, 8)]),)]

现在您可以使用简单的for循环进行比较:

for item in res:
    #do comparisons

答案 1 :(得分:1)

基于其他问题的代码,如果你想分别处理res的每个部分并累积结果,你可以这样做(使用@ utdemir答案中的方法):

from operator import itemgetter
print "Original List"
print '\n'.join(str(l) for l in phonemelist)
grp = itertools.groupby(phonemelist, itemgetter(1))
res = [tuple(v) for k, v in grp if k]
print '\n'.join(str(l) for l in res)
newlists = []
# for each part between the markers
for item in res:
    # update the ranges and add it to the overall list
    newlists.append(update_ranges(item))
print "\n after applying co-articulation rules"
print '\n\n'.join('\n'.join(str(i) for i in l) for l in newlists)