循环列表?

时间:2016-01-03 02:34:59

标签: python list while-loop pyscripter

我有一个数字列表,我想要这样,在输入3个数字后,他们会总结,除非其中一个数字是13,那么其余的数字将无效且不能总结。

因此,如果列表为[1, 13, 2],则结束总和为1。

total = 0
def lucky_sum():
    total = 0
    lucky_sum = []
    a = input("Input a number")
    b = input("Input a number")
    c = input("Input a number")
    lucky_sum.append(a)
    lucky_sum.append(b)
    lucky_sum.append(c)


while **What do I place here??** != 13:
    total += **and here**
    if i== 13:
        break
print total

lucky_sum()

3 个答案:

答案 0 :(得分:5)

您可以在不使用while循环的情况下执行此操作:

for i in lucky_sum():
    if i == 13:
        break

    total += i

编辑: 正如评论中所建议的,在lucky_sum中最后添加一个return语句。

答案 1 :(得分:3)

如果您真的想要,可以iter限制为最多3个,然后是from itertools import islice print sum(islice(iter(lambda: input('Input Number: '), 13), 3)) 的双参数版本,这样您的代码就可以变为:

lucky_sum()

为了保持简单,在def lucky_sum(): total = 0 for i in range(3): n = input('Input Number: ') if n == 13: break total += n return total print lucky_sum() 中使用一个循环3次,除非输入的数字是13,在这种情况下从循环中断并返回总数(默认为零)或者只是继续添加数字,例如:

import UIKit
import AVFoundation
import Accelerate

class ViewController: UIViewController {

var captureSession: AVCaptureSession?
var dataOutput: AVCaptureVideoDataOutput?
var customPreviewLayer: AVCaptureVideoPreviewLayer?

@IBOutlet weak var camView: UIView!

override func viewWillAppear(animated: Bool) {
    super.viewDidAppear(animated)
    captureSession?.startRunning()
    //setupCameraSession()
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    //captureSession?.startRunning()
    setupCameraSession()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func setupCameraSession() {
    // Session
    self.captureSession = AVCaptureSession()
    captureSession!.sessionPreset = AVCaptureSessionPreset1920x1080
    // Capture device
    let inputDevice: AVCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
    var deviceInput = AVCaptureDeviceInput()

    do {
        deviceInput = try AVCaptureDeviceInput(device: inputDevice)
    } catch let error as NSError {
        print(error)
    }
    if captureSession!.canAddInput(deviceInput) {
        captureSession!.addInput(deviceInput)
    }
    // Preview

    self.customPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    self.customPreviewLayer!.frame = camView.bounds
    self.customPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
    self.customPreviewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
    camView.layer.addSublayer(self.customPreviewLayer!)
    print("Cam layer added")

    self.dataOutput = AVCaptureVideoDataOutput()
    self.dataOutput!.videoSettings = [
        String(kCVPixelBufferPixelFormatTypeKey) : Int(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)
    ]

    dataOutput!.alwaysDiscardsLateVideoFrames = true
    if captureSession!.canAddOutput(dataOutput) {
        captureSession!.addOutput(dataOutput)
    }
    captureSession!.commitConfiguration()
    let queue: dispatch_queue_t = dispatch_queue_create("VideoQueue", DISPATCH_QUEUE_SERIAL)
    let delegate = VideoDelegate()
    dataOutput!.setSampleBufferDelegate(delegate, queue: queue)
}




 func captureOutput(captureOutput: AVCaptureOutput, didOutputSampleBuffer sampleBuffer: CMSampleBufferRef, fromConnection connection: AVCaptureConnection) {
    let imageBuffer: CVImageBufferRef = CMSampleBufferGetImageBuffer(sampleBuffer)!
    CVPixelBufferLockBaseAddress(imageBuffer, 0)
    // For the iOS the luma is contained in full plane (8-bit)
    let width: size_t = CVPixelBufferGetWidthOfPlane(imageBuffer, 0)
    let height: size_t = CVPixelBufferGetHeightOfPlane(imageBuffer, 0)
    let bytesPerRow: size_t = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0)
    let lumaBuffer: UnsafeMutablePointer = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0)
    let grayColorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
    let context: CGContextRef = CGBitmapContextCreate(lumaBuffer, width, height, 8, bytesPerRow, grayColorSpace, CGImageAlphaInfo.NoneSkipFirst.rawValue)!
    let dstImageFilter: CGImageRef = CGBitmapContextCreateImage(context)!
    dispatch_sync(dispatch_get_main_queue(), {() -> Void in
        self.customPreviewLayer!.contents = dstImageFilter as AnyObject
    })

}


}

答案 2 :(得分:1)

您也可以使用the sum() built-initertools.takewhile()执行此操作:

sum(itertools.takewhile(lambda i: i != 13, lucky_sum()))

sum()接受一个iterable并返回总和,takewhile()接受一个iterable并返回一个新的iterable,它给出值,直到给定的谓词失败。

这是一种更有效的方法,因为sum()非常快。

完整,类似这样的事情(使用list comprehension减少列表创建中的重复):

import itertools

def lucky_sum():
    return [input("Input a number") for _ in range(3)]

total = sum(itertools.takewhile(lambda i: i != 13, lucky_sum()))

print(total)

请注意,您可以在此处使用生成器表达式(普通括号而不是方括号),然后只有在用户输入13值或输入3个值时才会要求用户输入值,这可能是是理想的行为。