Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在Python中从列表中删除字符串元素。删除对我不起作用_Python 3.x_String_List_Function_Return - Fatal编程技术网

Python 3.x 如何在Python中从列表中删除字符串元素。删除对我不起作用

Python 3.x 如何在Python中从列表中删除字符串元素。删除对我不起作用,python-3.x,string,list,function,return,Python 3.x,String,List,Function,Return,我试图在选择字符串后将其从列表中删除,以避免再次获得相同的单词,但当我尝试删除字符串时。删除或。弹出不会删除该单词。这是为什么?我如何分类 我还试图创建一个单词的副本,以防它在从函数返回单词之前被删除,如果它已经被选中,这会影响单词吗 谢谢你的帮助,我对编程还不熟悉,你可能已经知道了 def choose_a_word_easy(): # function for choosing random easy word. words = ['ant', 'bee', 'cat', 'do

我试图在选择字符串后将其从列表中删除,以避免再次获得相同的单词,但当我尝试删除字符串时。删除或。弹出不会删除该单词。这是为什么?我如何分类

我还试图创建一个单词的副本,以防它在从函数返回单词之前被删除,如果它已经被选中,这会影响单词吗

谢谢你的帮助,我对编程还不熟悉,你可能已经知道了

def choose_a_word_easy():  # function for choosing random  easy word.
    words = ['ant', 'bee', 'cat', 'dog', 'egg', 'hat', 'golf', 'jelly', 'king', 'bird', 'hot', 'cold', 'fish', 'log',
             'dad', 'mum', 'goal', 'help', 'file', 'neat', 'car', 'moon', 'eye', 'tree', 'rice', 'ice', 'speed', 'rat',
             'water', 'rain', 'snow', 'spoon', 'light', 'gold', 'zoo', 'oil', 'goat', 'yoga', 'judo', 'japan', 'hello']

    pick = random.choice(words)  # randomly choose any word from the list.
    # p1 = pick
    words.remove(pick)
    return pick
通过在函数“选择单词”中声明列表,每次调用都会创建一个新列表。您希望在每次通话中重复使用相同的列表。通过在函数范围外创建列表并将其作为参数传递来实现

words = ['ant', 'bee', 'cat', 'dog', ...]

def pick_and_remove(lst):
    pick = random.choice(lst)
    lst.remove(pick)
    return pick

pick = pick_and_remove(words)

print(pick) # 'bee'
print(words) # ['ant', 'cat', 'dog', ...]
请注意,通过随机选取一个索引并弹出它,您的函数可以稍微提高效率

def pick_and_remove(lst):
    i = random.randrange(len(lst))
    return lst.pop(i)

你是如何检查这个词是否被删除的?当我运行这个程序时,这个词会在测验中弹出好几次