Python删除列表元素

2024-06-26 13:43:28 发布

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

如果我有一个python列表:

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

我如何使用itertools(或其他方式)来修改文本列表,以便它检查elem和{},如果它发现等于"",那么它会将它们从列表中删除呢。我只希望在找到elem + elemt1时修改列表(因此["fox" "", "is"]部分仍保留在列表中)。列表元素的顺序必须保持完整。在

^{pr2}$

Tags: thetext文本元素列表顺序is方式
3条回答

它的工作也有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)

您可以使用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-函数来提高效率。当转换为bool时,可以使用空字符串被视为False

^{pr2}$
from itertools import groupby, chain

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

结果:

^{pr2}$

使用groupby我们可以将连续元素与列表相同。然后检查每个列表的长度是否大于2,并且所有元素都是空字符串。然后我们保留我们想要的,并使用chain将列表展平。在

相关问题 更多 >