无法从 Python 中的列表中删除项目 - 问题在哪里?



我是新手,所以请忍受我:

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

这提高了价值:

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"one_answers" bad_directions [1]的类型"只是为了看看它们是否相同并且它们都是字符串。

请在此处放置[0]:

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

我认为这条线很夸张,并且易于错误:

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

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

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

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

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

deepcopy在那里制作了确切的deepCopy版本。我不知道您是否需要它,我只是添加了。

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

如果您不需要DeepCopy,则也不需要将说明保留为原始列表。然后可以使其更容易如下:

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

这是做到这一点的另一种方法:

随机导入方向= ['North','East'," South"," West"]index = random.randrange(len(Directions))#数字0、1、2或3good_direction =方向[索引]bad_directions =方向[:index]  方向[索引   1:]#除了所有方向[index]打印good_direction打印bad_directions 

示例输出是:

南['north','east','west']

如果您只需要bad_directions

,可以丢弃查找good_direction的行

您可以做不同的事情:

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

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

我同意以前的帖子 - 看起来像是一个巨大的过度杀伤,将列表转换为字符串然后正常化然后使用。

最新更新