我得到new_tag从一个表单文本字段与self.response.get(“new_tag”)和selected_tags从复选框字段与

self.response.get_all("selected_tags")

我把它们组合成这样:

tag_string = new_tag
new_tag_list = f1.striplist(tag_string.split(",") + selected_tags)

(f1。Striplist是一个去掉列表中字符串中的空格的函数。)

但如果tag_list是空的(没有输入新的标签),但有一些selected_tags, new_tag_list包含一个空字符串" "。

例如,从logging.info:

new_tag
selected_tags[u'Hello', u'Cool', u'Glam']
new_tag_list[u'', u'Hello', u'Cool', u'Glam']

我如何摆脱空字符串?

如果列表中有一个空字符串:

>>> s = [u'', u'Hello', u'Cool', u'Glam']
>>> i = s.index("")
>>> del s[i]
>>> s
[u'Hello', u'Cool', u'Glam']

但是如果没有空字符串:

>>> s = [u'Hello', u'Cool', u'Glam']
>>> if s.index(""):
        i = s.index("")
        del s[i]
    else:
        print "new_tag_list has no empty string"

但这就给出了:

Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    if new_tag_list.index(""):
        ValueError: list.index(x): x not in list

为什么会发生这种情况,我该如何解决它?


当前回答

作为一行:

>>> s = [u'', u'Hello', u'Cool', u'Glam']
>>> s.remove('') if '' in s else None # Does nothing if '' not in s
>>> s
['Hello', 'Cool', 'Glam']
>>> 

其他回答

添加这个答案是为了完整性,尽管它只在某些条件下可用。

如果你有一个非常大的列表,从列表的末尾删除可以避免CPython内部必须进行memmove,在这种情况下你可以重新排序列表。从列表的末尾删除可以获得性能增益,因为它不需要在您删除的项目之后移动每个项目—后退一步(1)。 对于一次性删除,性能差异可能是可以接受的,但如果您有一个很大的列表,需要删除许多项-您可能会注意到性能下降。

尽管不可否认,在这些情况下,执行完整的列表搜索也可能成为性能瓶颈,除非项主要位于列表的前面。

这种方法可以用于更有效的删除,只要重新排序列表是可以接受的。(2)

def remove_unordered(ls, item):
    i = ls.index(item)
    ls[-1], ls[i] = ls[i], ls[-1]
    ls.pop()

当项目不在列表中时,您可能希望避免引发错误。

def remove_unordered_test(ls, item):
    try:
        i = ls.index(item)
    except ValueError:
        return False
    ls[-1], ls[i] = ls[i], ls[-1]
    ls.pop()
    return True

虽然我用CPython测试了这一点,但很可能大多数/所有其他Python实现都使用数组在内部存储列表。因此,除非它们使用为有效调整列表大小而设计的复杂数据结构,否则它们可能具有相同的性能特征。

一个简单的测试方法是,比较从列表前面删除和删除最后一个元素的速度差异: Python -m timeit 'a = [0] * 100000' while a: a.m remove(0)' : Python -m timeit 'a = [0] * 100000' 'while a: a.pop()' (给出了一个数量级的速度差异,其中第二个例子使用CPython和PyPy更快)。

在这种情况下,您可以考虑使用set,特别是如果列表不是用来存储副本的。在实践中,你可能需要存储可变数据,不能添加到一个集合。还要检查btree的数据是否可以排序。

Eek,不要做任何复杂的事情:)

只需filter()你的标签。bool()对于空字符串返回False,因此代替

new_tag_list = f1.striplist(tag_string.split(",") + selected_tags)

你应该写

new_tag_list = filter(bool, f1.striplist(tag_string.split(",") + selected_tags))

或者更好的是,将这个逻辑放在striplist()中,这样它就不会首先返回空字符串。

如果index没有找到搜索的字符串,它会抛出您所看到的ValueError。要么 捕获ValueError:

try:
    i = s.index("")
    del s[i]
except ValueError:
    print "new_tag_list has no empty string"

或者使用find,在这种情况下返回-1。

i = s.find("")
if i >= 0:
    del s[i]
else:
    print "new_tag_list has no empty string"
try:
    s.remove("")
except ValueError:
    print "new_tag_list has no empty string"

注意,这只会从列表中删除空字符串的一个实例(您的代码也会这样做)。你的列表可以包含多个吗?

1 .使用过滤选项

new_tag_list = [u'', u'Hello', u'Cool', u'Glam']

new_tag_list= list(filter(None, new_tag_list))

2列表推导式也适用于除None之外的元素

new_tag_list = [u'', u'Hello', u'Cool', u'Glam']

[element for element in new_tag_list if element not in['']]