Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

python - Most elegant way to find the position of the odd one out

I have a list of 3 strings, two of which are always equal. I want to find the odd one out. The problems sound super simple but I haven't been able to find a truly elegant way to do it.

For example, the list, lst = ['foo', 'bar', 'foo'], should return 1. The way I am currently doing it is this:

f = lambda x, y, z: {(0, 0): 0, (0, 1): 1}.get((x == y, x == z), 2)
ans = f(*lst)

Is there a better way here?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could look for the first occurrence of the last value:

ans = (1, 0, 2)[lst.index(lst[2])]

Or if you're ok with index -1 instead of 2:

ans = 1 - lst.index(lst[2])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...