我想迭代一个包含列表和非列表元素组合的列表。这是一个例子:
a = [[1, 2, 3, 4, 5], 8, 9, 0, [1, 2, 3, 4, 5]]
我知道如何遍历强制列表列表,但在这种情况下我不知道如何做到这一点。我的目标是将嵌套列表的一个值与列表中的另一个值进行比较。例如,在这种情况下:[1, 2, 3, 4, 5]
和8
答案 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的答案略有不同。差异:
int
元素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)的东西可以用来获取对象的类型。