为什么函数未返回所需列表?

时间:2018-09-22 16:27:51

标签: python python-3.x function return

我的代码:

directions = ["north", "south", "east", "west"]
def scan(sentence):
    global sentence_list
    sentence_list = []
    sentence.split()
    for i in sentence:
        if i in directions:
            a = ('direction', i)
            sentence_list.append(a)
            del a
    return sentence_list

我试图拆分一个字符串并返回列表中元组中的单词,但是每当我使用它进行测试时,都会返回空列表。

这是我的输出:

PS C:\Users\dell 3521\lpythw\ex48> nosetests
F
======================================================================
FAIL: tests.lexicon_tests.test_directions
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\dell 3521\AppData\Local\Programs\Python\Python36- 
 32\lib\site-packages\nose-1.3.7-py3.6.egg\nose\case.py
    ", line 198, in runTest
    self.test(*self.arg)
  File "C:\Users\dell 3521\lpythw\ex48\tests\lexicon_tests.py", line 5, in 
test_directions
    assert_equal(lexicon.scan("north"), [('direction', 'north')])
AssertionError: Lists differ: [] != [('direction', 'north')]

Second list contains 1 additional elements.
First extra element 0:
('direction', 'north')

- []
+ [('direction', 'north')]

----------------------------------------------------------------------
Ran 1 test in 0.021s

FAILED (failures=1)

谢谢。

2 个答案:

答案 0 :(得分:2)

您必须将sentence重新分配为sentence.split()的返回值,或直接在sentence.split()上进行迭代,因为str.split()方法不会就地修改sentence ,但返回一个列表。

您也不需要del a语句。

将代码更改为

directions = ["north", "south", "east", "west"]

def scan(sentence):
    global sentence_list
    sentence_list = []
    for i in sentence.split():
        if i in directions:
            a = ('direction', i)
            sentence_list.append(a)

    return sentence_list 

或更简单的方法是使用list comprehension

directions = ["north", "south", "east", "west"]

def scan(sentence):
    global sentence_list
    sentence_list = [('direction', i) for i in sentence.split() if i in directions]

    return sentence_list

输出为

>>> scan("north")
[('direction', 'north')]

您可能希望您过分考虑在代码中使用global语句。 如various resources中所述,您要避免使用全局变量来提高代码的可读性和可维护性。

答案 1 :(得分:0)

str.split()方法不会就地修改字符串。您应该将str.split()的返回值分配给一个变量,或者在这种情况下,您可以简单地对其进行迭代:

sentence_list = []
for i in sentence.split():