我得到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

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


当前回答

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['']]

其他回答

这里有另一个简单的方法:

next((some_list.pop(i) for i, l in enumerate(some_list) if l == thing), None)

它不创建列表副本,不多次遍历列表,不需要额外的异常处理,并返回匹配的对象,如果不匹配则返回None。唯一的问题是这句话太长了。

一般来说,在寻找不抛出异常的一行程序解决方案时,next()是最佳选择,因为它是少数几个支持默认实参的Python函数之一。

如果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"

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

作为一行:

>>> 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']
>>> 

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()中,这样它就不会首先返回空字符串。