在Python中测试列表成员资格并同时获取索引

发布于 2024-12-08 18:02:52 字数 300 浏览 1 评论 0原文

编写以下内容似乎很愚蠢:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

爱殇璃 2024-12-15 18:02:52

另一个选项是 try/ except:

d = {}
try:
    d[x] = something_else
except KeyError:
    d[x] = something

与您的代码相同的结果。

编辑:好的,快速移动的目标。列表的习惯用法相同,但异常不同(IndexError)。

Another option is try/except:

d = {}
try:
    d[x] = something_else
except KeyError:
    d[x] = something

Same result as your code.

Edit: Okay, fast moving target. Same idiom for a list, different exception (IndexError).

吻风 2024-12-15 18:02:52

您的意思是您想要 setdefault(key[, default])

a = {}
a['foo'] # KeyError
a.setdefault('foo', 'bar') # key not exist, set a['foo'] = 'bar'
a.setdefault('foo', 'x') # key exist, return 'bar'

Do you mean you want setdefault(key[, default])

a = {}
a['foo'] # KeyError
a.setdefault('foo', 'bar') # key not exist, set a['foo'] = 'bar'
a.setdefault('foo', 'x') # key exist, return 'bar'
薆情海 2024-12-15 18:02:52

如果你有一个列表,你可以使用index,捕获ValueError(如果抛出):

yourList = []
try:
    i = yourList.index(x)
except ValueError:
    i = None

然后你可以测试i的值:

if i is not None:
    # Do things if the item was found.

If you have a list you can use index, catching the ValueError if it is thrown:

yourList = []
try:
    i = yourList.index(x)
except ValueError:
    i = None

Then you can test the value of i:

if i is not None:
    # Do things if the item was found.
腻橙味 2024-12-15 18:02:52

我认为你的问题让很多人感到困惑,因为你混合了字典和列表之间的语法。
如果:

L = []  # L is synonym for list and [] (braces) used to create list()

这里您正在列表中查找值,不是键,也不是字典中的值:

if x in L: 

然后您使用x看似作为键,但在列表中它是一个 int() 索引,并且执行 if x in L: 不会测试索引是否在 L 中,而是测试值是否在 L: 中,

L[x]=value

所以如果您打算查看值是否在 < code>L 列表做:

L = []                # that's a list and empty; and x will NEVER be in an empty list.
if x in L:            # that looks for value in list; not index in list
                      # to test for an index in a list do if len(L)>=x
   idx = L.index(x)
   L[idx] = something   # that makes L[index]=value not L[key]=value
else:
   # x is not in L so you either append it or append something_else
   L.append(x)

如果您使用:
L[x] = Somethingif x in L: 一起使用,那么拥有一个仅包含这些值的列表是有意义的:L=[ 0, 1 , 2, 3, 4, ...]L=[ 1.0, 2.0, 3.0, ...]

但我会提供这个:

L = []
L.extend(my_iterable)
coder0 = 'farr'
coder1 = 'Mark Byers'
if coder0 not in L:
    L.append(coder1)

奇怪的逻辑

I think your question confused many because you've mixed your syntax between dict and list.
If:

L = []  # L is synonym for list and [] (braces) used to create list()

Here you are looking for a value in a list, not a key nor a value in a dict:

if x in L: 

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:

L[x]=value

So if you intend to see if a value is in L a list do:

L = []                # that's a list and empty; and x will NEVER be in an empty list.
if x in L:            # that looks for value in list; not index in list
                      # to test for an index in a list do if len(L)>=x
   idx = L.index(x)
   L[idx] = something   # that makes L[index]=value not L[key]=value
else:
   # x is not in L so you either append it or append something_else
   L.append(x)

If you use:
L[x] = something together with if x in L: then it would make sense to have a list with only these values: L=[ 0, 1, 2, 3, 4, ...] OR L=[ 1.0, 2.0, 3.0, ...]

But I'd offer this:

L = []
L.extend(my_iterable)
coder0 = 'farr'
coder1 = 'Mark Byers'
if coder0 not in L:
    L.append(coder1)

Weird logic

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文