【问题标题】:Why the function is not returning the desired list?为什么函数没有返回所需的列表?
【发布时间】:2018-09-22 16:27:50
【问题描述】:

我的代码:

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.split() 不会就地修改sentence
  • 你应该尝试使用for i in sentence.split():
  • 原来是在源文件里,但是我发问题后忘记缩进代码了。现在已经纠正了。
  • 不要使用全局,del a 不是必需的,i 是一个词的坏名字。

标签: python python-3.x function return


【解决方案1】:

您必须将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 语句。 正如variousresources 中所述,您希望避免使用全局变量来提高代码的可读性和可维护性。

【讨论】:

  • sentence = sentence.split() 是多余的。 for i in sentence.split(): 就够了
  • 感谢您的回答。这很有帮助,但是我按照您的建议尝试删除 del a 并且它起作用了。不过,元组不应该是不可变的。
  • 是的,当然是。但是每次在循环中调用 a = ('direction', i) 时都会创建一个新元组。另一方面,尝试更改 a 的元素,例如 a[1] = 'north' 会导致 TypeError: 'tuple' object does not support item assignment
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2021-08-20
    • 1970-01-01
    • 2020-09-23
    • 2012-09-07
    • 2018-01-18
    • 1970-01-01
    • 2013-03-25
    • 2014-03-06
    相关资源
    最近更新 更多