开发者

working inside the boundaries denoted by 'None' inside a list

I have an input list for example :

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

I have to carry out comparisons between the values in the list. The item like (2,4) denotes a range. The 'None' entry in the list is like a boundary. The comparisons take place within the boundaries. So here, comparisons will be between a and b first. The comparison is basically between the values given with different conditions like if they are overlapping or not, since they are ranges. So the ranges change after comparing with the neighbour's ranges.

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   

Comparison is with simple rules for example, say comparing (2,4) and (3,9) then these two overlap partially so 开发者_StackOverflow中文版the common between them is chosen. Hence, the result is (3,4).

I have written the code for all the comparison rules but I tried them without boundaries. But they should be within boundaries. And I could not express the boundaries in code. Thank you.


You can group items by testing their second values is None or not, using 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)]),)]

Now you can use a simple for loop for comparisions:

for item in res:
    #do comparisons


Building on the code from your other questions, if you want to handle each part of res separately and accumulate the results, you can do it like this (using the method from @utdemir's answer):

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜