从lis中查找并删除列表

2024-05-15 00:43:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在试着找一些已经完成了我想做的事情的帖子,但是我什么也找不到。你知道吗

我有这张单子

rows =
[['Jan 31', ' 2014 19:48:30.096606000', '0x10', '0x00000000', '0x0f7864ef', '0x0f7864f1', '', 'blahblah', 'other \n'], 
['Jan 31', ' 2014 19:48:30.829329000', '0x10', '0x00000000', '0x0f920978', '0x0f92097a', '', 'blahblah', 'anotherr \n']]

我需要从列表中查找并删除一个列表,按第5项搜索,如下所示:

search == '0x0f7864ef'
if any(e[4] == search for e in rows):

如果搜索的var存在,那么我会得到一个True,但是我不知道如何从“行”中删除它。而像rows.remove(e)这样的操作只会返回一个错误

我试过在一个集合上循环并在找到时删除,但出现了一个错误。另外,我不想在集合/列表中循环。这就是我所尝试的:

>>> a = {( '1','da','vi' ), (2,'be','vi') }
>>> for item in a:
...   if 'da' in item:
...     a.remove(item)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Set changed size during iteration
>>> a
set([(2, 'be', 'vi')])

即使项目被删除,我得到一个错误。。。你知道吗

谢谢!你知道吗


Tags: in列表forsearchif错误beitem
2条回答

当您在列表上迭代时,不应该在列表中插入/删除元素。 相反,您可以使用高阶函数,如filter。你知道吗

在Python 2.7中:

>>> filter(lambda e: e[4] != '0x0f7864ef', rows)
[['Jan 31',
  ' 2014 19:48:30.829329000',
  '0x10',
  '0x00000000',
  '0x0f920978',
  '0x0f92097a',
  '',
  'blahblah',
  'anotherr \n']]

在python3.x中(filter返回一个生成器):

>>> filter(lambda e: e[4] != '0x0f7864ef', rows)
<builtins.filter at 0x7f76e2432810>

>>> list(filter(lambda e: e[4] != '0x0f7864ef', rows))
[['Jan 31',
  ' 2014 19:48:30.829329000',
  '0x10',
  '0x00000000',
  '0x0f920978',
  '0x0f92097a',
  '',
  'blahblah',
  'anotherr \n']]

为了可读性,您可能更喜欢定义一个命名函数,而不是使用lambda。你知道吗

只需创建一个新列表,其中包含已筛选的项目,如下所示:

new_list = [item for item in rows if search not in item]

这是一个列表理解,它是一个计算为列表的表达式。在for+if循环中写入上述内容的较长方法如下:

new_list = []
for item in rows:
   if search not in item:
       new_list.append(item)

修改正在循环的列表是一种非常糟糕的做法,这就是为什么标准做法是创建一个新的列表;要么使用列表理解,要么使用更传统的循环。你知道吗

相关问题 更多 >

    热门问题