example = [
('0-2', '0-0', '2-3', '0-1', '1-1', '1-0', '3-3', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'),
(4, 6, 7, 9, 10, 13, 17, 20, 24, 27, 29, 30, 31, 33, 35, 36, 37, 38, 45, 48, 51, 58, 61, 71, 79),
('4-2', '2-0', '0-1', '2-1', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'),
(6, 12, 13, 25, 30, 35, 37, 46, 47, 56, 58, '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-')
]
example.remove('-')
print(example) new_list.remove('-')
ValueError: list.remove(x): x not in list我应该如何进行,以使此错误不再发生?
预期结果:
[
('0-2', '0-0', '2-3', '0-1', '1-1', '1-0', '3-3'),
(4, 6, 7, 9, 10, 13, 17, 20, 24, 27, 29, 30, 31, 33, 35, 36, 37, 38, 45, 48, 51, 58, 61, 71, 79),
('4-2', '2-0', '0-1', '2-1'),
(6, 12, 13, 25, 30, 35, 37, 46, 47, 56, 58)
]发布于 2022-01-29 00:32:54
new_list是这样:
[('a', 'a', 'a', 'a'), ('b', 'b', 'b', 'b'), ('c', 'c', 'c', 'c'), ('d', 'd', 'd', 'd')]'d'不在里面。你想要吗?
new_list = [tup for tup in new_list if 'd' not in tup]
# [('a', 'a', 'a', 'a'), ('b', 'b', 'b', 'b'), ('c', 'c', 'c', 'c')]在本例中,我们将检查'd'是否在new_list中的每个元组中
编辑
考虑到新的问题公式,您要做的是过滤单个元组。您可以通过理解列表来完成这一任务:
example = [[item for item in tup if item != '-'] for tup in example]发布于 2022-01-29 01:02:18
要删除的项不在列表示例中,而是在列表中的元组中。但是,元组是不可变的,这意味着您不能对它们执行remove。相反,您可以使用(生成器)理解来过滤掉不需要的项目:
example = [
('0-2', '0-0', '2-3', '0-1', '1-1', '1-0', '3-3', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'),
(4, 6, 7, 9, 10, 13, 17, 20, 24, 27, 29, 30, 31, 33, 35, 36, 37, 38, 45, 48, 51, 58, 61, 71, 79),
('4-2', '2-0', '0-1', '2-1', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-'),
(6, 12, 13, 25, 30, 35, 37, 46, 47, 56, 58, '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-')
]
output = [tuple(x for x in tup if x != '-') for tup in example]
print(output)
# [('0-2', '0-0', '2-3', '0-1', '1-1', '1-0', '3-3'), (4, 6, 7, 9, 10, 13, 17, 20, 24, 27, 29, 30, 31, 33, 35, 36, 37, 38, 45, 48, 51, 58, 61, 71, 79), ('4-2', '2-0', '0-1', '2-1'), (6, 12, 13, 25, 30, 35, 37, 46, 47, 56, 58)]发布于 2022-01-29 00:32:03
一个最好的方法是看看new_list在记忆中持有什么,就像这样.

因此,正如您所看到的,new_list持有一个元组的列表,这就是当您试图从其中删除一个元素'd‘时会收到错误的原因。
https://stackoverflow.com/questions/70901471
复制相似问题