2

我想遍历一个包含列表和非列表元素混合的列表。这是一个例子:

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

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

4

4 回答 4

4

这是你想要的吗:

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
于 2012-05-18T20:28:52.910 回答
3

与jgritty的答案略有不同的版本。区别:

  • 我们使用filter()内置int从列表中提取元素
  • 我们将整数保存在一个集合中,而不是一个list
  • 我们遍历 的副本a,以便我们可以同时安全地从a自身中删除元素
  • 使用列表推导删除已经在主列表中的嵌套列表的成员

    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
    
于 2012-05-18T21:15:16.290 回答
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)
于 2012-05-18T20:23:32.387 回答
0

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

我现在不记得确切的命令了,但是可以使用 type(x) 之类的东西来获取对象的类型。

于 2012-05-18T20:23:07.283 回答