从Python中的列表列表中删除元素

时间:2019-12-18 21:28:24

标签: python list

在给定初始列表列表(如以下列表)的情况下,如何从列表列表中删除在“ 3”之前放置“ 5”的每个列表?

[('3', '3', '3'), ('3', '3', '5'), ('3', '5', '3'), ('3', '5', '5'), ('5', '3', '3'), ('5', '3', '5'), ('5', '5', '3'), ('5', '5', '5')]

我尝试过

for i in list_ck:
   for j in range(0,2):
      if (i[j]=='5' and i[j+1]=='3'):
         list_ck.remove(i)

但这不起作用

3 个答案:

答案 0 :(得分:2)

如果是字符串而不是元组,则更容易测试5是否在3之前出现。因此我们可以使用''.join将它们转换为字符串。

>>> data = [('3', '3', '3'), ('3', '3', '5'), ('3', '5', '3'), ('3', '5', '5'), ('5', '3', '3'), ('5', '3', '5'), ('5', '5', '3'), ('5', '5', '5')]
>>> [r for r in data if '53' not in ''.join(r)]
[('3', '3', '3'), ('3', '3', '5'), ('3', '5', '5'), ('5', '5', '5')]

这假设您只想在3之前测试5,并且不适用于元组中的字符串可能会出现的更一般的情况。成为'53'自己。但这足以满足您的要求。

一个更通用的解决方案是使用正则表达式,并加入像,这样的字符,其中的任何字符串都不包含:

>>> data = [('5', '3', '1'), ('53', '1', '1'), ('5', '1', '3')]
>>> import re
>>> pattern = re.compile('(^|,)5,(.*,)*3(,|$)')
>>> [r for r in data if not pattern.search(','.join(r))]
[('53', '1', '1')]

在此模式(^|,)5,(.+,)*3(,|$),的开头或之后与5匹配,后跟一个逗号,后面跟任意数量以逗号结尾的事物,后跟一个3,前一个是逗号或字符串的结尾。

答案 1 :(得分:1)

您可以使用条件列表理解:

# List of Tuples (lot).
list_of_tups = [('3', '3', '3'), ('3', '3', '5'), ('3', '5', '3'), ('3', '5', '5'), ('5', '3', '3'), ('5', '3', '5'), ('5', '5', '3'), ('5', '5', '5')]

>>> [tup for tup in list_of_tups 
     if not any((a == '5' and b == '3') for a, b in zip(tup, tup[1:]))]
[('3', '3', '3'), ('3', '3', '5'), ('3', '5', '5'), ('5', '5', '5')]

要就地修改列表而不是创建新列表,请创建一个需要删除的项目的索引,然后以相反的顺序将其弹出。

idx = [n for n, tup in enumerate(list_of_tups) 
       if any((a == '5' and b == '3') for a, b in zip(tup, tup[1:]))]
for i in reversed(idx):
    list_of_tups.pop(i)

>>> list_of_tups
[('3', '3', '3'), ('3', '3', '5'), ('3', '5', '5'), ('5', '5', '5')]

答案 2 :(得分:-1)

尝试用相同的参数创建另一个列表(不要复制它们,创建新的),然后从第二个列表中删除()

tab = [('3', '3', '3'), ('3', '3', '5'), ('3', '5', '3'), ('3', '5', '5'), ('5', '3', '3'), ('5', '3', '5'), ('5', '5', '3'), ('5', '5', '5')]    
tab2 = [('3', '3', '3'), ('3', '3', '5'), ('3', '5', '3'), ('3', '5', '5'), ('5', '3', '3'), ('5', '3', '5'), ('5', '5', '3'), ('5', '5', '5')]
for i in tab:
    for j in range(0,2):
        if i[j]=='5' and i[j+1]=='3':
            tab2.remove(i)
            break