调用“del"函数调用结果导致“SyntaxError: can't delete function call" [英] Calling "del" on result of Function call results in "SyntaxError: can't delete function call"

查看:103
本文介绍了调用“del"函数调用结果导致“SyntaxError: can't delete function call"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的例子:

random_tile = random.choice(tiles)
del random_tile

它首先将 tiles 列表中的一个随机元素分配给一个变量,然后在该变量上调用一个函数.

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)

我们会得到一个SyntaxError: can't delete function call.我尝试了 eval() 没有运气.怎么解决?

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

我想要做的是从 tiles 列表中随机删除一个元素.除了使用 random.randint() 作为索引之外,我以为我找到了一种更紧凑的方法,但我想不是.

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.

是否有 Pythonic/传统的方式来做到这一点?

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

推荐答案

del 不是函数,而是创建del 语句 例如del var.您不能将其用作函数或在函数上使用,它只能应用于变量名称、变量名称列表或订阅和切片,例如

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[:]

要删除随机项目,您可以试试这个

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]

这篇关于调用“del"函数调用结果导致“SyntaxError: can't delete function call"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆