【问题标题】:Iteration over a list迭代列表
【发布时间】:2014-10-25 04:59:15
【问题描述】:

我正在努力解决以下问题:

编写一个函数 has23(nums),它接受一个长度为 2 的 int 列表,如果它包含 23,则返回 True

我的代码:

def has23(nums):
    for i in nums:
        if i == 2 or i == 3:
            return True
        return False

测试:

has23([2, 5]) 预期:True 得到:True

has23([42, 53]) 预期:False 得到:False

has23([4, 3]) 预期:True 得到:**False**

has23([1, 2]) 预期:True 得到:**False**

我不知道为什么它会返回False 给我,而在最后两个测试中它应该是True

【问题讨论】:

  • 对无效回滚表示歉意。
  • 不需要循环:def has23(nums): return 2 in nums or 3 in nums

标签: loops python-3.x iteration


【解决方案1】:

缩进很重要。您只迭代一次,因为 return False 出现在您的循环中,导致它提前退出。将其更改为:

def has23(nums):
    for i in nums:
        if i == 2 or i == 3:
            return True
    return False

正如@dawg 所说,您不需要循环。

def has23(nums):
    return 2 in nums or 3 in nums

// Python interpreter courtesy of http://www.skulpt.org/
// of which I have no affiliation
function outf(text) {
    var mypre = document.getElementById("output");
    mypre.innerHTML = mypre.innerHTML + text;
}

function builtinRead(x) {
    if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
        throw "File not found: '" + x + "'";
    return Sk.builtinFiles["files"][x];
}

function runit() {
    var prog = document.getElementById("yourcode").value;
    var mypre = document.getElementById("output");
    mypre.innerHTML = '';
    Sk.canvas = "mycanvas";
    Sk.pre = "output";
    Sk.configure({
        output: outf,
        read: builtinRead
    });
    try {
        eval(Sk.importMainWithBody("<stdin>", false, prog));
    } catch (e) {
        alert(e.toString())
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/skulpt/skulpt-dist/master/skulpt.min.js" type="text/javascript"></script>
<script src= "https://raw.githubusercontent.com/skulpt/skulpt-dist/master/skulpt-stdlib.js" type="text/javascript"></script>

<form style='float:left; margin: 5px'>
    <textarea cols="40" id="yourcode" rows="10">def has23(nums):
        return 2 in nums or 3 in nums
print(has23([2, 5]))
print(has23([42, 53]))
print(has23([4, 3]))
print(has23([1, 2]))
    </textarea><br>
    <button onclick="runit()" type="button">Run</button>
</form>
<pre id="output"></pre>

【讨论】:

  • 或者,也许更好,def has_ns(li, *ns): return any(n in li for n in ns) 然后使用可变的测试元组调用:has_ns([5,4,3], 2, 3)
猜你喜欢
  • 2012-10-11
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 2023-03-23
  • 2010-09-07
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多