Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Finding all the elements in a list between two elements (not using index, and with wrap around)

I'm trying to figure out a way to find all the elements that appear between two list elements (inclusive) - but to do it without reference to position, and instead with reference to the elements themselves. It's easier to explain with code:

I have a list like this:

['a','b','c','d','e']

And I want a function that would take, two arguments corresponding to elements eg. f('a','d'), and return the following:

['a','b','c','d']

I'd also like it to wrap around, eg. f('d','b'):

['d','e','a','b']

I'm not sure how to go about coding this. One hacky way I've thought of is duplicating the list in question (['a','b','c','d','e','a','b','c','d','e']) and then looping through it and flagging when the first element appears and when the last element does and then discarding the rest - but it seems like there would be a better way. Any suggestions?

question from:https://stackoverflow.com/questions/65648090/finding-all-the-elements-in-a-list-between-two-elements-not-using-index-and-wi

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

1 Reply

0 votes
by (71.8m points)
def foo(a, b):
    s, e = [a.index(x) for x in b]
    if s <= e:
        return a[s:e+1]
    else:
        return a[s:] + a[:e+1]

print(foo(['a','b','c','d','e'], ['a', 'd']))  # --> ['a', 'b', 'c', 'd']

print(foo(['a','b','c','d','e'], ['d', 'b']))  # --> ['d', 'e', 'a', 'b']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...