假设我有以下列表:
l = ["watermelon", "banana", "orange", "apple"]
我想写一个函数,返回列表中另一个元素之前的元素。例如:
>> is_before("banana", "watermelon")
>> False
>> is_before("banana", "apple")
>> True
编写这样一个函数的最古怪的方法是什么?
你可以做(假设没有重复(:
l = ["watermelon", "banana", "orange", "apple"]
indeces = {w: i for i, w in enumerate(l)}
def is_previous(x, y):
return indeces[x] < indeces[y]
>>> is_previous("banana", "watermelon")
False
>>> is_previous("banana", "apple")
True
这不会处理任何参数不在初始列表中的情况。
mylist = ["watermelon", "banana", "orange", "apple"]
def is_before(prev_item, target, arr):
return prev_item in arr[:arr.index(target)]
>>>is_before("banana", "apple", mylist)
True
>>>is_before("banana", "watermelon", mylist)
False
如果你想处理重复,你可以使用类似的东西
def find_item_last_index(count, item, arr, index=0):
# A recursive function for finding the last index of an item in a list
if count == 1:
return index + arr.index(item)
return (find_item_last_index(count-1, item, arr[arr.index(item)+1:],
index+arr.index(item)+1))
def is_before(prev_item, target, arr):
return prev_item in arr[: find_item_last_index(arr.count(target), target, arr)]
mylist = ["watermelon", "apple", "banana", "orange", "apple"]
>>>is_before("banana", "apple", mylist)
True
>>>is_before("banana", "watermelon", mylist)
False