我正在迭代Python中的元组列表,并且如果它们符合某些条件,我会尝试删除它们.
for tup in somelist:
if determine(tup):
code_to_remove_tup
Run Code Online (Sandbox Code Playgroud)
我应该用什么代替code_to_remove_tup
?我无法弄清楚如何以这种方式删除项目.
我的问题很简单:我有一个很长的元素列表,我想迭代并根据条件检查每个元素.根据条件的结果,我想删除列表的当前元素,并像往常一样继续迭代它.
我已经在这个问题上阅读了其他几个主题.提出两种解决方案.要么从列表中创建一个字典(这意味着要复制已经填满我所有RAM的所有数据).要么反向走列表(这打破了我想要实现的算法的概念).
有没有更好或更优雅的方式呢?
def walk_list(list_of_g):
g_index = 0
while g_index < len(list_of_g):
g_current = list_of_g[g_index]
if subtle_condition(g_current):
list_of_g.pop(g_index)
else:
g_index = g_index + 1
Run Code Online (Sandbox Code Playgroud) 我有一个解决方法来解决以下问题.该解决方法将是一个for循环,其中包含一个包含在输出中的测试,如下所示:
#!/usr/bin/env python
def rem_dup(dup_list):
reduced_list = []
for val in dup_list:
if val in reduced_list:
continue
else:
reduced_list.append(val)
return reduced_list
Run Code Online (Sandbox Code Playgroud)
我问下面的问题,因为我很想知道是否有列表理解解决方案.
鉴于以下数据:
reduced_vals = []
vals = [1, 2, 3, 3, 2, 2, 4, 5, 5, 0, 0]
Run Code Online (Sandbox Code Playgroud)
为什么
reduced_vals = = [x for x in vals if x not in reduced_vals]
Run Code Online (Sandbox Code Playgroud)
产生相同的清单?
>>> reduced_vals
[1, 2, 3, 3, 2, 2, 4, 5, 5, 0, 0]
Run Code Online (Sandbox Code Playgroud)
我认为它与检查output(reduced_vals
)作为列表赋值的一部分有关.我很好奇,但确切的原因.
谢谢.