小编And*_*das的帖子

嵌套列表理解有两个列表

我理解简单列表理解是如何工作的,例如:

[x*2 for x in range(5)] # returns [0,2,4,6,8]
Run Code Online (Sandbox Code Playgroud)

而且我也理解嵌套列表comprehesion的工作原理:

w_list = ["i_have_a_doubt", "with_the","nested_lists_comprehensions"]

# returns the list of strings without underscore and capitalized
print [replaced.title() for replaced in [el.replace("_"," ")for el in w_list]]
Run Code Online (Sandbox Code Playgroud)

所以,当我尝试这样做的时候

l1 = [100,200,300]
l2 = [0,1,2]
[x + y for x in l2 for y in l1 ]
Run Code Online (Sandbox Code Playgroud)

我期待这个:

[101,202,303]
Run Code Online (Sandbox Code Playgroud)

但我得到了这个:

[100,200,300,101,201,301,102,202,302]
Run Code Online (Sandbox Code Playgroud)

所以我有一个更好的方法解决问题,这给了我想要的东西

[x + y for x,y in zip(l1,l2)]
Run Code Online (Sandbox Code Playgroud)

但我不理解第一个代码上9个元素的返回

python nested list-comprehension

37
推荐指数
3
解决办法
5万
查看次数

Python类导入错误

我正在研究python中的类和OO,尝试从包中导入类时发现了一个问题。项目结构和类描述如下:

ex1/
    __init__.py
    app/
        __init__.py
        App1.py
    pojo/
        __init__.py
        Fone.py
Run Code Online (Sandbox Code Playgroud)

这些课程:

Fone.py

class Fone(object):

    def __init__(self,volume):
        self.change_volume(volume)

    def get_volume(self):
        return self.__volume

    def change_volume(self,volume):
        if volume >100:
            self.__volume = 100
        elif volume <0:
            self.__volume = 0
        else:
            self.__volume = volume

volume = property(get_volume,change_volume)
Run Code Online (Sandbox Code Playgroud)

App1.py

from ex1.pojo import Fone

if __name__ == '__main__':
    fone = Fone(70)
    print fone.volume

    fone.change_volume(110)
    print fone.get_volume()

    fone.change_volume(-12)
    print fone.get_volume()

    fone.volume = -90
    print fone.volume

    fone.change_volume(fone.get_volume() **2)
    print fone.get_volume()
Run Code Online (Sandbox Code Playgroud)

当我尝试从ex1.pojo import Fone使用时,引发以下错误:

fone = Fone(70) …
Run Code Online (Sandbox Code Playgroud)

python import class

2
推荐指数
1
解决办法
3722
查看次数

标签 统计

python ×2

class ×1

import ×1

list-comprehension ×1

nested ×1