【问题标题】:Having trouble using int(), split(), and nosetests with Python在 Python 中使用 int()、split() 和鼻子测试时遇到问题
【发布时间】:2019-05-13 21:49:25
【问题描述】:

这是我的第一篇文章。

我有一段代码正在尝试对其进行测试。

有一个非常简单的解决方法可以让这段代码运行,那就是将整数放在引号中。

我想要完成的是拥有一个在字典中使用字符串和整数的字典。这是我的带扫描功能的字典。

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() 的位置,以便在“3 91234”上运行 split() 时,它将返回两个整数并正确使用我的词典来回调适当的值?

感谢您的帮助!

【问题讨论】:

    标签: python string dictionary integer nose


    【解决方案1】:

    您可以使用 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 否则它将无法获取存储为字符串的数字键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多