迭代Python中的整数和列表列表

时间:2012-05-18 20:16:52

标签: python list

我想迭代一个包含列表和非列表元素组合的列表。这是一个例子:

a = [[1, 2, 3, 4, 5], 8, 9, 0, [1, 2, 3, 4, 5]] 

我知道如何遍历强制列表列表,但在这种情况下我不知道如何做到这一点。我的目标是将嵌套列表的一个值与列表中的另一个值进行比较。例如,在这种情况下:[1, 2, 3, 4, 5]8

4 个答案:

答案 0 :(得分:3)

这就是你想要的:

thelist = [[1, 2, 3, 4, 5], 5, 6, 7, 8, 10, [9, 0, 1, 8]]
# Remove the 5 from the first inner list because it was found outside.
# Remove the 8 from the other inner list, because it was found outside.
expected_output =[[1, 2, 3, 4], 5, 6, 7, 8, 10, [9, 0, 1]]

这是一种方法:

thelist = [[1, 2, 3, 4, 5], 5, 6, 7, 8, [9, 0, 1, 8]]

expected_output =[[1, 2, 3, 4], 5, 6, 7, 8, [9, 0, 1]]

removal_items = []

for item in thelist:
    if not isinstance(item, list):
        removal_items.append(item)

for item in thelist:
    if isinstance(item, list):
        for remove in removal_items:
            if remove in item:
                item.remove(remove)

print thelist

assert thelist == expected_output

答案 1 :(得分:3)

jgritty的答案略有不同。差异:

  • 我们使用filter()内置功能从列表中提取int元素
  • 我们将整数保留在set而不是list
  • 我们遍历a的副本,以便我们可以安全地从a本身同时删除元素
  • 使用list comprehension删除已列在主列表中的嵌套列表的成员

    a = [[1, 2, 3, 4, 5], 5, 6, 7, 8, [9, 0, 1, 8]]
    print a
    
    numbers = set(filter(lambda elem: type(elem) is not list, a))
    
    for elem in a:
        if type(elem) is list:
            elem[:] = [number for number in elem if number not in numbers]
    
    print a
    

答案 2 :(得分:2)

a = [[1, 2, 3, 4, 5], 8, 9, 0, [1, 2, 3, 4, 5]]
for x in a:
    if type(x) is list:
        for y in x:
            print y
    else:
        print x

或使用

isinstance(x, list)

答案 3 :(得分:0)

您可以检查迭代的对象是否为ListType(http://docs.python.org/library/types.html)并进一步迭代。

我现在无法记住确切的命令,但有类似(x)的东西可以用来获取对象的类型。