开发者

Test for list membership and get index at the same time in 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 th开发者_运维技巧is 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.


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).


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'


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜