以自定义方式麻烦拆箱清单

时间:2019-07-11 08:44:22

标签: python python-3.x generator yield

我正在尝试解压缩一些我在get_item()函数中产生的列表。我知道如果使用return而不是yield可以得到理想的结果。

我尝试过:

def get_item():
    yield ["k","y","t"]

if __name__ == '__main__':
    for item in get_item():
        print(item)

我得到的输出:

['k', 'y', 't']

我想要得到的输出:

k
y
t

我应该进行哪些可能的改变以保持预期的yield效果?

3 个答案:

答案 0 :(得分:9)

从Python 3.3开始,您可以使用yield from

def get_item():
    yield from ["k","y","t"]

if __name__ == '__main__':
    for item in get_item():
        print(item)

输出:

k
y
t

yield from是Python 3.3中引入的新技巧,只是其中的一小部分:

  

对于简单的迭代器,可迭代的收益本质上只是可迭代项目的简化形式:yield item:

(重点是我的)

答案 1 :(得分:1)

您可以使用*运算符获得所需的结果:

def get_item():
    yield ["k","y","t"]

if __name__ == '__main__':
    print('\n'.join(*get_item()))

打印:

k
y
t

答案 2 :(得分:-2)

尝试以下方法:

func setupScrollView() {
    DispatchQueue.main.async {
        self.scrollView.layoutIfNeeded() // in order to get correct frame

        let numberItem = 6
        let spaceBetweenView: CGFloat = 20
        let firstAndLastSpace: CGFloat = spaceBetweenView / 2            
        let width = self.scrollView.frame.size.width
        let height = self.scrollView.frame.size.height
        let numberOfView: CGFloat = CGFloat(numberItem)
        let scrollViewContentSizeWidth = numberOfView * width

        self.scrollView.contentSize = CGSize(width: scrollViewContentSizeWidth, height: height)

        for index in 0..<numberItem {
            let xCoordinate = (CGFloat(index) * (width)) + firstAndLastSpace
            let viewFrame = CGRect(x: xCoordinate, y: 0, width: width - spaceBetweenView, height: height)
            let view = UIView()
            view.backgroundColor = .red

            view.frame = viewFrame
            self.scrollView.addSubview(view)
        }
    }
}