从 DEEP 嵌套列表中删除子列表
Remove sublist from DEEP nestedlist
我正在努力处理一些嵌套列表。
简而言之,在列表列表中我有一些列表包含几个值
biglist = [[['strings', '632'], ['otherstrings', 'hey']],[['blabla', '924'], ['histring', 'hello']]]
从这个嵌套列表中,我想删除其中出现 'hello'
字符串的子列表。
我试过这个:
for sub_line in big_list:
if 'hello' in sub_line:
big_list.remove(sub_line)
现在,如果我在循环外打印新的 big_list
,我会得到旧列表,因为我没有将更新后的列表分配给新列表。但是,如果我分配给一个新列表,例如:
for sub_line in big_list:
if 'hello' in sub_line:
updated_list = big_list.remove(sub_line)
print(updated_list)
我得到一个 AttributeError: 'NoneType' object has no attribute 'remove'
。
那么这有什么问题呢?
我不能使用列表索引,因为我的真实列表很大而且目标值并不总是在同一个地方。
我已经检查过其他问题,但没有任何效果。
谢谢大家!
以下适合我。您需要从列表中删除 sub_line(不是行)。
big_list = [['strings', '632', 'otherstrings', 'hey'],['blabla', '924', 'histring', 'hello']]
print(big_list)
for sub_line in big_list:
if 'hello' in sub_line:
big_list.remove(sub_line)
print(big_list)
for sublist in biglist:
if 'hello' in sublist:
updated_list=biglist.remove(sublist)
print(updated_list)
以上代码的输出是 None
因为 remove()
没有 return 任何值,即它 return 是 None
。所以你不应该在列表中分配 remove()
的 return 值。
我认为这可能会在您使用 updated_list
.
时引起一些问题
如果你经常有两层嵌套(不是我标记的 DEEP),你可以组合 this answer from the dupe marking by @pault with list flattening:
biglist = [[['strings', '632'], ['otherstrings', 'hey']],[['blabla', '924'], ['histring', 'hello']]]
token = 'hello'
smalllist = [x for x in biglist if not token in [j for i in x for j in i]]
# smalllist
# Out[17]: [[['strings', '632'], ['otherstrings', 'hey']]]
我正在努力处理一些嵌套列表。 简而言之,在列表列表中我有一些列表包含几个值
biglist = [[['strings', '632'], ['otherstrings', 'hey']],[['blabla', '924'], ['histring', 'hello']]]
从这个嵌套列表中,我想删除其中出现 'hello'
字符串的子列表。
我试过这个:
for sub_line in big_list:
if 'hello' in sub_line:
big_list.remove(sub_line)
现在,如果我在循环外打印新的 big_list
,我会得到旧列表,因为我没有将更新后的列表分配给新列表。但是,如果我分配给一个新列表,例如:
for sub_line in big_list:
if 'hello' in sub_line:
updated_list = big_list.remove(sub_line)
print(updated_list)
我得到一个 AttributeError: 'NoneType' object has no attribute 'remove'
。
那么这有什么问题呢? 我不能使用列表索引,因为我的真实列表很大而且目标值并不总是在同一个地方。 我已经检查过其他问题,但没有任何效果。 谢谢大家!
以下适合我。您需要从列表中删除 sub_line(不是行)。
big_list = [['strings', '632', 'otherstrings', 'hey'],['blabla', '924', 'histring', 'hello']]
print(big_list)
for sub_line in big_list:
if 'hello' in sub_line:
big_list.remove(sub_line)
print(big_list)
for sublist in biglist:
if 'hello' in sublist:
updated_list=biglist.remove(sublist)
print(updated_list)
以上代码的输出是 None
因为 remove()
没有 return 任何值,即它 return 是 None
。所以你不应该在列表中分配 remove()
的 return 值。
我认为这可能会在您使用 updated_list
.
如果你经常有两层嵌套(不是我标记的 DEEP),你可以组合 this answer from the dupe marking by @pault with list flattening:
biglist = [[['strings', '632'], ['otherstrings', 'hey']],[['blabla', '924'], ['histring', 'hello']]]
token = 'hello'
smalllist = [x for x in biglist if not token in [j for i in x for j in i]]
# smalllist
# Out[17]: [[['strings', '632'], ['otherstrings', 'hey']]]