简体   繁体   中英

Why the function is not returning the desired list?

My code:

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

I am trying to split a string and return the words in a tuple within a list, but whenever i test it using returns empty list.

Here's my output:

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)

Thanks in advance.

You have to reassign sentence to the return value of sentence.split() or iterate directly over sentence.split() , because the str.split() method does not modify sentence in place, but returns a list instead.

Also you do not need the del a statement.

Change your code to

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 

Or a even shorter way is using 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

The output is

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

And you may want the over think the use of the global statement in your code. As explained in various resources , you want to avoid using global variables for the readability and maintainability of your code.

The str.split() method does not modify the string in-place. You should assign the returning value of str.split() to a variable, or in this case, you can simply iterate over it instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM