在 Python 中使用 int()、split() 和 nosetests 时遇到问题
Having trouble using int(), split(), and nosetests with Python
这是我的第一个post。
我有一段代码正在尝试 运行 鼻子测试。
制作此代码有一个非常简单的修复方法 运行,那就是将整数放在引号中。
我想要完成的是有一个字典,在字典中使用字符串和整数。这是我的带有扫描功能的字典。
lexicon = {
'1234': 'number',
3: 'number',
91234: 'number'
}
def scan(sentence):
results = []
words = sentence.split()
for word in words:
word_type = lexicon.get(word)
results.append((word_type, word))
return results
上面的代码被导入到我的包含这段代码的测试文件中。
from nose.tools import *
from ex48 import lexicon
def test_numbers():
assert_equal(lexicon.scan('1234'), [('number', '1234')])
result = lexicon.scan('3 91234')
assert_equal(result, [('number', 3),
('number', 91234)])
“1234”部分 运行 很好。
但是,代码中是否有我可以使用 int() 的位置,以便当 split() 在“3 91234”上 运行 时,它将 return 两个整数并使用我的词库字典正确地回调相应的值?
感谢您的帮助!
您可以使用 isnumeric() 方法检查字符串是否为数字,然后转换为 int。
lexicon = {
'1234': 'number',
3: 'number',
91234: 'number'
}
def scan(sentence):
results = []
words = sentence.split()
for word in words:
if word.isnumeric(): #change
word = int(word) #change
word_type = lexicon.get(word)
results.append((word_type, word))
return results
请注意,在此更改后,您需要将所有数字键存储为 int,否则它不会获取存储为字符串的数字键。
这是我的第一个post。
我有一段代码正在尝试 运行 鼻子测试。
制作此代码有一个非常简单的修复方法 运行,那就是将整数放在引号中。
我想要完成的是有一个字典,在字典中使用字符串和整数。这是我的带有扫描功能的字典。
lexicon = {
'1234': 'number',
3: 'number',
91234: 'number'
}
def scan(sentence):
results = []
words = sentence.split()
for word in words:
word_type = lexicon.get(word)
results.append((word_type, word))
return results
上面的代码被导入到我的包含这段代码的测试文件中。
from nose.tools import *
from ex48 import lexicon
def test_numbers():
assert_equal(lexicon.scan('1234'), [('number', '1234')])
result = lexicon.scan('3 91234')
assert_equal(result, [('number', 3),
('number', 91234)])
“1234”部分 运行 很好。
但是,代码中是否有我可以使用 int() 的位置,以便当 split() 在“3 91234”上 运行 时,它将 return 两个整数并使用我的词库字典正确地回调相应的值?
感谢您的帮助!
您可以使用 isnumeric() 方法检查字符串是否为数字,然后转换为 int。
lexicon = {
'1234': 'number',
3: 'number',
91234: 'number'
}
def scan(sentence):
results = []
words = sentence.split()
for word in words:
if word.isnumeric(): #change
word = int(word) #change
word_type = lexicon.get(word)
results.append((word_type, word))
return results
请注意,在此更改后,您需要将所有数字键存储为 int,否则它不会获取存储为字符串的数字键。