无法从Python中的列表中删除项目 - 哪里是捕获?

时间:2014-03-07 10:36:53

标签: python list python-2.7

我是新手所以请耐心等待我:

import random

directions = ['north', 'east', 'south', 'west']
bad_directions = directions[:]

good_direction = random.sample(directions,1)
good_direction = str(good_direction).replace('[','').replace(']','')

bad_directions.remove(good_direction)
print bad_directions

这引发了ValueError:

Traceback (most recent call last):
  File "directions.py", line 9, in <module>
    bad_directions.remove(good_direction)
ValueError: list.remove(x): x not in list

我尝试检查“good_direction”和“bad_directions [1]”的类型,看看它们是否相同而且它们都是字符串。

6 个答案:

答案 0 :(得分:2)

我认为这条线太过分且容易出错:

good_direction = str(good_direction).replace('[','').replace(']','')

如果你想检索random.sample(directions,1)返回的字符串,你可以这样做:

good_direction=random.sample(directions,1)[0]

您的代码失败了,因为您错过了replace来自检索到的字符串的内容。

我跟踪了您的代码,替换后的结果字符串为"'abc'"

>>>import random
>>>l=['abc' for i in range(10)]
>>>s=random.sample(l,1)
>>>s
['abc']
>>>str(s)
"['abc']"
>>>s1=str(s).replace('[','').replace(']','')
>>>s1
"'abc'"    # auch! the single quotes remain there!
>>>s1 in l
False

答案 1 :(得分:2)

请把[0]放在这里:

good_direction = random.sample(directions,1)[0]

答案 2 :(得分:1)

每个代码的好方向返回的字符串不同于方向列表中的内容。以下是输出。

>>> good_direction
"'east'"
>>> good_direction
"'east'"
>>> good_direction in directions
False

--- 可能是下面的代码将实现你想要实现的目标。

>>> good_direction = random.choice(directions)
>>> good_direction
'east'
>>> bad_directions.remove(good_direction)
>>> print bad_directions
['north', 'south', 'west']

答案 3 :(得分:1)

深度显示可以制作精确的深度复制版本的方向。我不知道你是否需要它,我只是加了它。

https://ideone.com/9D8FZI

# your code goes here
import random
import copy

directions = ['north', 'east', 'south', 'west']

bad_directions = copy.deepcopy(directions)

good_directions = random.choice(directions)
bad_directions.remove(good_directions)

print good_directions,bad_directions

如果您不需要深度复印,那么您也不需要保留原始列表的指示。然后可以更容易如下:

https://ideone.com/C49ziQ

# your code goes here
import random

bad_directions = ['north', 'east', 'south', 'west']

good_directions = random.choice(bad_directions)
bad_directions.remove(good_directions)

print good_directions,bad_directions

答案 4 :(得分:0)

这是另一种方法:

import random

directions = ['north', 'east', 'south', 'west']
index = random.randrange (len (directions)) # number 0, 1, 2 or 3
good_direction = directions[index]
bad_directions = directions[:index] + directions[index + 1:] # all but directions[index]
print good_direction
print bad_directions

示例输出是:

south
['north', 'east', 'west']

如果您只需要good_direction,则可以放弃查找bad_directions的行。

答案 5 :(得分:0)

你可以这样做:

bad_directions.pop(random.randrange(len(bad_directions)))

del(bad_directions[random.randrange(len(bad_directions))])

我同意上一篇文章 - 它看起来像是一个巨大的过度杀伤,将列表转换为字符串然后规范化,然后使用它。