Calling “del” on result of Function call results in “SyntaxError: can't delete function call”

↘锁芯ラ 提交于 2019-12-24 13:28:42

问题


Consider below example:

random_tile = random.choice(tiles)
del random_tile

It first assigns a random element from the list tiles to a variable, and then calls a function on that variable.

Then if we want to shorten the code as follows:

del random.choice(tiles)

We would get a SyntaxError: can't delete function call. I tried eval() with no luck. How can this be solved?

EDIT:

What I am trying to do is to remove a element from the tiles list at random. I thought I found a more compact way of doing it other than using random.randint() as the index, but I guess not.

Is there a pythonic/conventional way of doing this otherwise?


回答1:


del is not a function, it is a keyword to create del statements e.g. del var. You can't use it as a function or on a function, it can only be applied to a variable name, list of variable names or subscriptions and slicings e.g.

del a
del a,b
del l[0]
del l[:]

To remove the random item you can try this

random_tile.remove(random.choice(tiles))

BUT it is not best way to remove items because it could mean a internal search for items and item comparison, also won't work if items are not unique, so best would be to get random index and delete that

index = random.randint(0, len(l)-1)
del l[index]



回答2:


If you're trying to actually modify your tiles list, your first attempt doesn't do it either. It just assigns to your variable, then wipes that variable. That's because del works on the variable itself, not what it points to. Most other functions work on the value some variable points to. So unless you actually need to use del, what you're trying to do will work fine.

Also, if you are trying to use del, i'm pretty sure you're using it wrong. If you elaborate more on what you're trying to do, we can probably help you.




回答3:


There are a number of ways to remove a random element from a list. Here's one.

>>> import random
>>> my_list = [1, 2, 3, 4, 5]
>>> my_list.remove(random.choice(my_list))
>>> my_list
[1, 2, 4, 5]



回答4:


Given a list tiles this does the trick:

import random
tiles.remove(random.choice(tiles))


来源:https://stackoverflow.com/questions/13128856/calling-del-on-result-of-function-call-results-in-syntaxerror-cant-delete-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!