リストとリスト以外の要素が混在するリストを繰り返し処理したいと考えています。次に例を示します。
a = [[1, 2, 3, 4, 5], 8, 9, 0, [1, 2, 3, 4, 5]]
リストの必須リストを反復処理する方法は知っていますが、この場合はその方法がわかりません。私の目的は、ネストされたリストの 1 つの値をリスト内の別の値と比較することです。たとえば、この場合:[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) のようなものがあります。