简体   繁体   English

Python - 如何使用while循环和for循环从列表中随机删除一个项目直到列表为空

[英]Python - how to randomly remove an item from the list until list is empty using both a while-loop and for-loop

I have been trying to remove a random item from a list using a while-loop and for-loop.我一直在尝试使用 while 循环和 for 循环从列表中删除一个随机项。 For the while-loop, it should print it to the console until the list -days- is empty.对于 while 循环,它应该将其打印到控制台,直到列表 -days- 为空。

Here is my code thus far-到目前为止,这是我的代码-

while-loop: while循环:

days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']

while len(days) > 0:
    days = days.pop(0)

for-loop: for循环:

for day in range(len(days)):
    day = days.pop(0)

output: for-loop: output:for循环:

AttributeError: 'str' object has no attribute 'pop'

I am a novice programmer and I am struggling to correct this issue.我是一名新手程序员,我正在努力纠正这个问题。 Is there a way to pop items from the while loop?有没有办法从while循环中弹出项目? Can someone explain the attribute error and why I am getting this message?有人可以解释属性错误以及为什么我收到此消息吗?

if you want to remove randomly如果你想随机删除

days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']

from random import randrange
while len(days) > 0:
    index=randrange(0,len(days))
    days.pop(index)
    print(days)

print('End')

Your first loop is the right way to do it.您的第一个循环是正确的方法。 but you are overwriting the list with the first element.但是您正在用第一个元素覆盖列表。 You want你要

while days:
    day = days.pop(0)

The for loop is not good practice. for循环不是一个好习惯。 It is dangerous to modify a list while you are iterating through it.在迭代列表时修改列表是危险的。 Think about it.想想看。 First time through the loop, "day" is 0. You pop element 0. Now, the element that used to be [1] is in the [0] slot, but when you loop again, day will be 1 and your numbering is off.第一次循环,“day”是0。你弹出元素0。现在,曾经是[1]的元素在[0]槽中,但是当你再次循环时, day将是1,你的编号是离开。

And AGAIN, you are overwriting the loop variable ( day ) with the result of the pop.再一次,您正在用 pop 的结果覆盖循环变量 ( day )。 Be careful with your variable names.小心你的变量名。

To remove randomly you can use numpy to generate a random number, and then use.pop() to remove an item from the list and print it at the same time:要随机删除,您可以使用 numpy 生成一个随机数,然后使用.pop() 从列表中删除一个项目并同时打印它:

import numpy as np
days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']

while days:
    index = int(np.round((np.random.rand(1)-0.5)*len(days)))
    print(days.pop(index))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM