在Python中测试列表成员资格并同时获取索引
编写以下内容似乎很愚蠢:
L = []
if x in L:
L[x] = something
else:
L[x] = something_else
这不是对 x 执行两次查找吗?我尝试使用index(),但是当找不到该值时会出现错误。
理想情况下,我想说:
if x is in L, save that index and:
...
我可以理解这可能是一个初学者的 python 习惯用法,但它似乎无法搜索。谢谢。
It seems silly to write the following:
L = []
if x in L:
L[x] = something
else:
L[x] = something_else
Doesn't this perform the look-up for x twice? I tried using index(), but this gives an error when the value is not found.
Ideally I would like to say like:
if x is in L, save that index and:
...
I can appreciate that this might be a beginner python idiom, but it seems rather un-search-able. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另一个选项是 try/ except:
与您的代码相同的结果。
编辑:好的,快速移动的目标。列表的习惯用法相同,但异常不同(IndexError)。
Another option is try/except:
Same result as your code.
Edit: Okay, fast moving target. Same idiom for a list, different exception (IndexError).
您的意思是您想要
setdefault(key[, default])
Do you mean you want
setdefault(key[, default])
如果你有一个列表,你可以使用
index
,捕获ValueError
(如果抛出):然后你可以测试i的值:
If you have a list you can use
index
, catching theValueError
if it is thrown:Then you can test the value of i:
我认为你的问题让很多人感到困惑,因为你混合了字典和列表之间的语法。
如果:
这里您正在列表中查找值,不是键,也不是字典中的值:
然后您使用x看似作为键,但在列表中它是一个 int() 索引,并且执行
if x in L:
不会测试索引是否在 L 中,而是测试值是否在 L: 中,所以如果您打算查看值是否在 < code>L 列表做:
如果您使用:
L[x] = Something
与if x in L:
一起使用,那么拥有一个仅包含这些值的列表是有意义的:L=[ 0, 1 , 2, 3, 4, ...]
或L=[ 1.0, 2.0, 3.0, ...]
但我会提供这个:
奇怪的逻辑
I think your question confused many because you've mixed your syntax between dict and list.
If:
Here you are looking for a value in a list, not a key nor a value in a dict:
And then you use x seemingly intended as a key but in lists it's an int() index and doing
if x in L:
doesn't test to see if index is in L but if value is in L:So if you intend to see if a value is in
L
a list do:If you use:
L[x] = something
together withif x in L:
then it would make sense to have a list with only these values:L=[ 0, 1, 2, 3, 4, ...]
ORL=[ 1.0, 2.0, 3.0, ...]
But I'd offer this:
Weird logic