从列表中删除一个元素并返回结果

3
我可以帮您翻译。需要翻译的内容是有关IT技术的,您希望生成一个类似于以下格式的列表:
['ret-120','ret-115','ret-110',....'ret-5','ret5',....'ret240']

请注意,列表中没有ret0元素。因此,我需要从由range函数填充的列表中将其删除。我尝试了以下方法:
['ret'+str(x) for x in list(range(-120,241,5)).remove(0)]

然而,这会产生一个错误:
TypeError: 'NoneType' object is not iterable

有没有可能只用一行代码就能实现这个目标?

4个回答

3
您想要实现的最简单方法是在列表推导式中添加条件语句:
lst = ['cumRet'+str(x) for x in xrange(-120,241,5) if x != 0]
# This part:                                       ^^^^^^^^^

我还删除了不必要的列表创建,并将range更改为xrange(请注意,此range->xrange更改仅适用于Python2)。


2
您的 NoneType 错误是因为 list.remove(index) 在原地修改,所以返回 None
因此,您正在尝试循环 [for x in None]
2行可替换的方式(带有;)。
tmp = list(range(-120,241,5));tmp.remove(0)
['ret'+str(x) for x in list(range(-120,241,5)).remove(0)]

谢谢,你知道写代码的正确方式吗? - undefined
@user2854008,由于remove是一个方法,所以无法将其转换为一行代码。但你可以将它拆分成三行,查看我的修改。 - undefined

1
问题在于list.remove()方法会直接改变列表并返回None,但是当x为零时,你可以这样跳过它:
['ret'+str(x) for x in range(-120, 241, 5) if x]

如果你正在使用Python 2,可以将range()替换为xrange(),这样可以避免创建包含所有整数值的临时列表。

0

remove() 返回 None

列表的 remove() 方法返回 None,因此 'NoneType' 对象不可迭代。

示例:

>>> b = list(range(-120,241,5)).remove(0)
>>> b
>>> print b
None

我们将创建一个列表变量,然后从中删除0
演示:
>>> tmp = list(range(-120,241,5))
>>> tmp.remove(0)
>>> ['cumRet'+str(x) for x in tmp]
['cumRet-120', 'cumRet-115', 'cumRet-110', 'cumRet-105', 'cumRet-100', 'cumRet-95', 'cumRet-90', 'cumRet-85', 'cumRet-80', 'cumRet-75', 'cumRet-70', 'cumRet-65', 'cumRet-60', 'cumRet-55', 'cumRet-50', 'cumRet-45', 'cumRet-40', 'cumRet-35', 'cumRet-30', 'cumRet-25', 'cumRet-20', 'cumRet-15', 'cumRet-10', 'cumRet-5', 'cumRet5', 'cumRet10', 'cumRet15', 'cumRet20', 'cumRet25', 'cumRet30', 'cumRet35', 'cumRet40', 'cumRet45', 'cumRet50', 'cumRet55', 'cumRet60', 'cumRet65', 'cumRet70', 'cumRet75', 'cumRet80', 'cumRet85', 'cumRet90', 'cumRet95', 'cumRet100', 'cumRet105', 'cumRet110', 'cumRet115', 'cumRet120', 'cumRet125', 'cumRet130', 'cumRet135', 'cumRet140', 'cumRet145', 'cumRet150', 'cumRet155', 'cumRet160', 'cumRet165', 'cumRet170', 'cumRet175', 'cumRet180', 'cumRet185', 'cumRet190', 'cumRet195', 'cumRet200', 'cumRet205', 'cumRet210', 'cumRet215', 'cumRet220', 'cumRet225', 'cumRet230', 'cumRet235', 'cumRet240']
>>> 

异常处理:

在从列表中删除元素时,最佳实践是进行异常处理,因为如果列表中不存在该元素,则会引发ValueError异常。

演示:

>>> l = [4,6,8]
>>> l.remove(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> 
>>> try:
...   l.remove(3)
... except ValueError:
...   print "List not contains remove element."
... 
List not contains remove element.
>>> 

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