当前位置: 代码迷 >> python >> 为什么该函数没有返回所需的列表?
  详细解决方案

为什么该函数没有返回所需的列表?

热度:110   发布时间:2023-07-14 09:52:38.0

我的代码:

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)

提前致谢。

您必须将sentence重新分配给sentence.split()的返回值或直接迭代sentence.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 

或者更短的方法是使用

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语句。 正如,为了代码的可读性和可维护性,您希望避免使用全局变量。

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

sentence_list = []
for i in sentence.split():
  相关解决方案