Python删除列表元素

3
如果我有一个 Python 列表:
text = ["the", "red", "", "", "fox", "", "is"]

我该如何使用itertools(或其他方法)修改文本列表,以便检查elemelem+1,如果找到等于""的元素,则将其从列表中删除。只有在找到elem + elemt1时才希望修改列表(因此["fox" "", "is"]部分仍然保留在列表中)。列表元素的排序必须保持不变。
text = ["the", "red", "fox", "", "is"]

所以你想从列表中删除空值并用“”替换? - Mohamad Ibrahim
2
["the", "red", "", "", "", "fox", "", "is"]怎么处理?应该删除所有三个空字符串还是保留其中一个? - Psidom
4个回答

2
from itertools import groupby, chain

print list(chain(*[
    l for l in [list(it) for _, it in groupby(text)] if l[:2] != ['', '']
]))

结果:

['the', 'red', 'fox', '', 'is']

使用groupby,我们可以将连续的元素视为列表。然后,我们检查每个列表是否具有大于两个且所有元素都为空字符串的长度。然后,我们保留所需内容并使用chain展开列表。

使用 zip_longest - Daniel
那个结果看起来不像问题中期望的结果。 - user2390182
谢谢,我真的很喜欢浏览每个人的解决方案,特别是这个。我确实有一个关于chain([list])的问题。当你添加时,它会将[[lista]]展平为[lista]。这只适用于chain吗?还是它是Python的一般能力? - user386211

2
你可以使用 itertools.groupby:
import itertools

new = []
for item, group in itertools.groupby(text):
    group = list(group)
    if item != '' or len(group) == 1:
        new.extend(group)

>>> new
['the', 'red', 'fox', '', 'is']

使用groupby函数可以更加高效。可以利用将空字符串转换为False的事实:

import itertools

new = []
for item, group in itertools.groupby(text, bool):
    group = list(group)
    if item or len(group) == 1:
        new.extend(group)

>>> new
['the', 'red', 'fox', '', 'is']

这与我的解决方案逻辑相同,但更易读,因此更具有教育意义 ;) - user2390182

0

它可以处理超过2个空格的情况

text = ["the", "red", "","", "", "fox", "", "is"]
new_text = []

text_len = len(text);
print(text_len)
i = 0;
while(i < text_len):
    if (text[i] == "" and text[i + 1] == ""):
        i += 1;
        while(True):
                if (text[i] == "" and text[i + 1] == ""):
                    i+=1;
                else:
                        break;

    else :
        new_text.append(text[i]);
    i += 1;
print(new_text)

-3
for t in text:
  if not t:
     text.remove(t)

1
永远不要更改你正在迭代的列表。 - Daniel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接