在.split()列表中整合字符串时出错

时间:2016-06-01 16:19:59

标签: python try-catch nose

我开始学习python可以有人请告诉我如何确定这个鼻子测试:

from nose.tools import *

    from lexicon.lexicon import lexicon
    def test_directions():
        assert_equal(lexicon.scan("north"), [('direction', 'north')])
        result = lexicon.scan("north south east")
        assert_equal(result, [('direction', 'north'),
                              ('direction', 'south'),
                              ('direction', 'east')])
    def test_numbers():
        assert_equal(lexicon.scan("1234"), [('number', 1234)])
        result = lexicon.scan("3 91234")
        assert_equal(result, [('number', 3),
                              ('number', 91234)])

我使用下面的代码来传递第一个测试,但无法通过test_numbers()

directions = ['north','south','east','east','down','up','left','right','back','front']
class lexicon:
    @staticmethod
    def scan(d):
        list1 = [('direction', x) for x in d.split() if x in directions]
        try:
            list2 = [('number',int(x)) for x in d.split() if int(x) in xrange(999999)]
        except ValueError:
            return None   
        return list1 + list2

我在想我是在滥用try。请帮助我

2 个答案:

答案 0 :(得分:0)

此代码:

try:
    x = something_that_raises_an_error()
except:
    return y

未设置x = y。它只是在except块内执行语句,因此返回y

当您运行scan("north")并进入except ValueError:块时,它会返回None。这意味着函数在那里结束scan("north") is None。将return None替换为list2 = []return list1

(另外,如果您的代码集list2 = None由于list1 + None失败而无法正常运行 - 您无法将列表添加到非列表中,None是不是清单)

但这只会让你到目前为止,因为现在当你传递一个单词和数字混合时,你将得不到任何数字。您需要在循环中使用try块,以便它可以为列表中的每个值执行正确的操作。

答案 1 :(得分:0)

这是问题的完整解决方案

directions =['north','south','east','east','down','up','left','right','back','front']
numbers = xrange(999999999)
class lexicon:
    @staticmethod
    def scan(d):
        list2=d.split()
        list1=[]
        list3=[]
        try:
            for x in d.split(): 

                if int(x) in xrange(999999999):
                    a = x

                    list1.append(a)
                    list2.remove(a)
                else:
                    print "yes"
        except:
            list99=[]
        for x in d.split():
            if x in directions:
                z2 = ("direction" , x)
                list3.append(z2)
            elif x in list1:
                z2 = ("number" , int(x))
                list3.append(z2)
            elif x in list2:
                z2 = ("error" , x)
                list3.append(z2)
        return list3

这样就完美了