代码之家  ›  专栏  ›  技术社区  ›  Alex

不理解用python将循环转换为列表的代码

  •  1
  • Alex  · 技术社区  · 6 年前

    我是python的新手,我得到了以下代码:

    nlist = autoscaling_connection.get_all_launch_configurations()
    name = "CONFIG"    
    versions = [x.name[len(name):] for x in nlist
                    if (x.name.startswith(name) and is_number(x.name[len(name):]))]
    

    我知道for循环被连接到版本列表中,但我不理解赋值:

    [x.name[len(name):]
    
    3 回复  |  直到 6 年前
        1
  •  3
  •   dangee1705    6 年前

    我会把整个代码展开,然后再看一遍

    versions = [x.name[len(name):] for x in nlist
                if (x.name.startswith(name) and is_number(x.name[len(name):]))]
    

    等同于

    versions = []
    for x in nlist:
        if (x.name.startswith(name) and is_number(x.name[len(name):])):
             versions.append(x.name[len(name):])
    

    x.name[len(name):]
    

    len(name) x.name

    my_list = [1, 2, 3, 4, 5]
    

    我知道

    my_list[2:]
    

    [3, 4, 5]
    

    我希望这有帮助。如果您想进一步了解python切片表示法,我可以推荐另一个问题: Understanding Python's slice notation

        2
  •  0
  •   Michael Ekoka    6 年前

    x 是一个列表和 i 是一个索引(整数)。

    x[i:] 
    

    表示“所有项目” 从索引开始 “一直到最后”

    你也可以

    x[i:j]
    

    “中的所有项目” 从索引开始 j "

    x[:j]
    

    “中的所有项目” 从头开始一直到,但不包括 j "

    y = x[:]
    

    y = x[2:9:3]
    

    “x的每三个元素,从索引2开始,在索引9之前结束。”

    我建议在Python中查找列表属性。

        3
  •  0
  •   Patrick Artner    6 年前

    略为完整(但估计)的代码:

    class K:
        """A class that has a name property"""
        def __init__(self,name):
            self.name = name
    
    # a prefix to look for            
    name = "Fiat "
    
    
    # a list of objects that have a name - some starting with our name
    nlist = [K("Fiat 2"), K("Fiat 4"), K("Fiat 2711999"), K("Fiat Dupe 09"), K("DosntFly 0815")]
    
    def is_number(text):
        """Test if the text is an integer."""
        try:
            int(text.strip())
        except:
            return False
        return True
    
    
    versions = [x.name[len(name):] for x in nlist
                    if (x.name.startswith(name) and is_number(x.name[len(name):]))]
    
    print(versions)
    

    输出:

    ['2', '4', '2711999']
    

    列表测试每个元素的理解能力 nlist

    它只会让东西进入 versions if (x.name.startswith(name) and is_number(x.name[len(name):] .

    意思是:每个类都是实例 name 必须从变量开始 名称 名称 有,必须检查 True is_number()

    "Fiat Dupe 09"  # not in the list, because "Dupe 09" is not True
    "DosntFly 0815" # not in the list, because not starting with "Fiat "