-4

我有一个遵循法定编号方案的号码列表

列表如下所示 -

['1', '1', '1.1', '1.2', '1.3', '1.4', '1.5', '2', '1.6', '2', '2.1', '2.2', '2.3', '2.4', '3', '2.5', '3', '3.1', '3.2', '4', '5', '4', '6', '6.1', '6.2', '9333', '6.3', '6.4', '5', '6.5', '6.6', '6.7', '6.8', '6.9', '6.10', '6', '7']

但是,此列表中有“整数”闯入者(与方案不一致的数字)。例如列表顶部的第一个“1”,在“1.6”之前的“2​​”。是否有已知的算法或模式来识别不一致的数字并将它们从列表中删除?

编辑:由于某些人不清楚这个问题,我发布了一个合法编号的方案是什么样的:

['1','1.1','1.2','1.3','2','2.1','3','3.1','3.2'....]

但是请注意,我无法将其与静态列表进行比较,因为这只是一个编号方案。'2' 后面可以跟着 '2.1' 然后回到 '3' 或者可以跟着 '2.1','2.2' 然后回到 '3'。

4

3 回答 3

4
for a,b in zip(mylist, mylist[1:]):
    if a==b:
        print('Value {} is repeated'.format(a))
    elif a > b:
        print('Either {} or {} is out of order'.format(a,b))

根据您的数据,这给出了

Value 1 is repeated
Either 2 or 1.6 is out of order
Either 3 or 2.5 is out of order
Either 5 or 4 is out of order
Either 9333 or 6.3 is out of order
Either 6.4 or 5 is out of order
Either 6.9 or 6.10 is out of order
Either 6.10 or 6 is out of order

或者,

mylist = sorted(set(mylist))

自动删除重复项并将所有内容整理好。

编辑: Mark Byers 提出了一个很好的观点,即 6.9 / 6.10 排序不正确;我看到的唯一解决方案是解析字符串,以便我们比较整数,如下所示:

mylist = sorted(set(mylist), key=lambda s:map(int, s.split('.')))

结果是

['1', '1.1', '1.2', '1.3', '1.4', '1.5', '1.6', '2', '2.1', '2.2', '2.3', '2.4', '2.5', '3', '3.1', '3.2', '4', '5', '6', '6.1', '6.2', '6.3', '6.4', '6.5', '6.6', '6.7', '6.8', '6.9', '6.10', '7', '9333']
于 2012-07-06T20:35:32.870 回答
2

您基本上想将其与列表的排序版本进行比较

for a, b in zip(numbers, sorted(numbers, key=lambda x: x.split('.'))):
    if a != b:
       print('error at ' + a)
       # or do something else
于 2012-07-06T19:34:49.907 回答
1

尝试这个:

def get_next_dotted_term(s, i):
    for x in s[i + 1:]:
        if '.' in x:
            return int(x.partition('.')[0])

def make_valid(s):
    result = []
    current = 0

    for i, x in enumerate(s):
        if '.' in x:
            result.append(x)
        else:
            ix = int(x)
            nextdot = get_next_dotted_term(s, i)
            if current + 1 == ix and (ix <= nextdot or not nextdot):
                result.append(x)
                current += 1
            else:
                print "Error: " + x
    return result

print make_valid(['1','1.1','2','1.2','2','3','3.1','3.2','4','3.3','3.4'])

结果:

错误:2
错误:4
['1', '1.1', '1.2', '2', '3', '3.1', '3.2', '3.3', '3.4']
于 2012-07-08T12:07:32.193 回答