我想遍历一个包含列表和非列表元素混合的列表。这是一个例子:
a = [[1, 2, 3, 4, 5], 8, 9, 0, [1, 2, 3, 4, 5]]
我知道如何遍历列表的强制性列表,但在这种情况下,我不知道该怎么做。我的目标是将嵌套列表的一个值与列表中的另一个值进行比较。例如在这种情况下:[1, 2, 3, 4, 5]
和8
这是你想要的吗:
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
与jgritty的答案略有不同的版本。区别:
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
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)
您可以检查迭代的对象是否是 ListType (http://docs.python.org/library/types.html) 并进一步迭代它。
我现在不记得确切的命令了,但是可以使用 type(x) 之类的东西来获取对象的类型。