您如何简化这些循环?

时间:2019-09-21 01:22:30

标签: python python-3.x

func endMotionMonitoring(){
    if manager == nil && motionManager == nil { return }
    manager!.stopActivityUpdates()
    manager = nil

    motionManager!.stopAccelerometerUpdates()
    motionManager = nil
}

我有这些循环,想知道是否有任何方法可以简化它。

4 个答案:

答案 0 :(得分:2)

同时测试两个条件以将其减少到一个循环:

def funny_phrases(lst):
    funny = []
    for word in lst:
        if len(word) >= 6 and word.endswith('y'):
            funny.append(word)
    return funny

然后可以将其翻译为列表理解,从而留下:

def funny_phrases(lst):
    return [word for word in lst if len(word) >= 6 and word.endswith('y')]

请注意,除了对循环的改进外,我还做了两个小改动:

  1. 我将变量名称更改为lst,以避免对list构造函数进行名称更改(如果需要,它将阻止您使用它)
  2. 我将使用幻数进行切片的方法更改为命名方法.endswith('y'),该方法更具自记录性(并且不需要像切片那样的临时str)。

答案 1 :(得分:0)

您未使用嵌套循环,但可以使用filter

import React, { Component } from "react";

class TextBox extends Component {
  textLineHeight = 19;
  minRows = 3;

  style = {
    minHeight: this.textLineHeight * this.minRows + "px",
    resize: "none",
    lineHeight: this.textLineHeight + "px",
    overflow: "hidden"
  };

  update = e => {
    e.target.rows = 0;
    e.target.rows = ~~(e.target.scrollHeight / this.textLineHeight);
  };

  render() {
    return (
      <textarea rows={this.minRows} onChange={this.update} style={this.style} />
    );
  }
}

export default TextBox;

顺便说一句,如您所见,我将参数def funny_phrases(words): funny = filter(lambda word: len(word) >= 6, words) return list(filter(lambda word: word[-1:] is "y", funny)) 重命名为list,因为它覆盖了list()函数。尝试不要将words叫到您的列表,而要使用更多解释性名称。

或一行:

list

或进行一次迭代:

def funny_phrases(words):
    return list(filter(lambda word: word[-1:] is "y", filter(lambda word: len(word) >= 6, words)))

或者,如果您更喜欢列表理解:

def funny_phrases(words):
    return list(filter(lambda word: len(word) >= 6 and word[-1:] is "y", words))

此外,还有一些可以改进的地方:

def funny_phrases(words):
    return [word for word in words if len(word) >= 6 and word[-1:] is "y"]

那不好,相反:

word[-1:] is "y"

这更冗长,更容易理解。

所以您的决赛应该是以下两者之一:

word.endswith("y")

我会使用列表理解功能,因为我认为它们比较冗长,但这取决于您。

正如@ShadowRanger所言,列表理解是完成此任务的更好选择。它们看起来更好,在这种情况下(使用lambda)它们比def funny_phrases(words): return [word for word in words if len(word) >= 6 and word.endswith("y")] def funny_phrases(words): return list(filter(lambda word: len(word) >= 6 and word.endswith("y"), words)) 更快。

答案 2 :(得分:0)

您可以使用Public Sub CodeInForm1() Dim frm As Form frm = New Form2() ' Code Concepts for VB Parent Child in MDI and Non MDI scenarios frm.MdiParent = Me ' MDI Concept frm.Owner = Me ' No MDI but still linked frm.Show(Me) ' Anoter way to link Forms when spawning a new one (No MDI) frm.Show() ' No Specific Parent Assigned End Sub 的高级切片功能

numpy

答案 3 :(得分:-1)

def funny_phrases(list):
    return [(l) for l in list if len(l)>6 and l[len(l)-1] == 'y']

print(funny_phrases(["absolutely", "fly", "sorry", "taxonomy", "eighty", "excellent"]))

['absolutely', 'taxonomy']
相关问题