【问题标题】:Print index of sublists with error?打印错误子列表的索引?
【发布时间】:2013-08-03 01:41:22
【问题描述】:

我有一个由一定长度的子列表组成的列表,有点像[["a","b","c","d"],["a","b","c","d"],["a","b","c","d","e"]]。我想要做的是找到没有特定长度的子列表的索引,然后将该索引打印出来。例如,在示例列表中,最后一个子列表的长度不是四,所以我会打印list 2 does not have correct length。这是我目前所拥有的:

for i in newlist:
    if len(i) == 4:
        print("okay")
elif len(i) != 4:
    ind = i[0:]     #this isnt finished; this prints out the lists with the not correct length, but not their indecies 
    print("not okay",ind)

提前致谢!

【问题讨论】:

    标签: list python-3.x indexing


    【解决方案1】:

    当您需要索引和对象时,通常可以使用enumerate,它会产生(index, element) 元组。例如:

    >>> seq = "a", "b", "c"
    >>> enumerate(seq)
    <enumerate object at 0x102714eb0>
    >>> list(enumerate(seq))
    [(0, 'a'), (1, 'b'), (2, 'c')]
    

    等等:

    newlist = [["a","b","c","d"],["a","b","c","d"],["a","b","c","d","e"]]
    
    for i, sublist in enumerate(newlist):
        if len(sublist) == 4:
            print("sublist #", i, "is okay")
        else:
            print("sublist #", i, "is not okay")
    

    生产

    sublist # 0 is okay
    sublist # 1 is okay
    sublist # 2 is not okay
    

    【讨论】:

    • 这真的很有帮助!谢谢!只是想知道,有没有办法没有对象,只有索引?
    • 不过,您需要让对象取其长度。您可以使用for i in range(len(newlist)):,然后使用newlist[i],但这被认为是非pythonic 风格。
    【解决方案2】:

    我认为 DSM 得到了您想要的答案,但您也可以使用 index method 并编写如下内容:

    new_list = [["a","b","c","d"],["a","b","c","d"],["a","b","c","d","e"]]
    size_filter = 4
    # all values that are not 4 in size
    indexes = [new_list.index(val) for val in new_list if len(val)!=size_filter]
    # output values that match
    for index in indexes:
        print("{0} is not the correct length".format(index))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 2016-05-21
      • 2019-11-12
      • 2020-12-02
      • 2021-08-26
      • 1970-01-01
      相关资源
      最近更新 更多