[英]Most pythonic way to find relation between two elements in a list
Let's say I have the following list:假设我有以下列表:
l = ["watermelon", "banana", "orange", "apple"]
And I want to write a function that returns whatever the element is before another element in the list.我想编写一个函数,该函数返回列表中另一个元素之前的元素。 for example:
例如:
>> is_before("banana", "watermelon")
>> False
>> is_before("banana", "apple")
>> True
What is the most pythonic way to write such a function?编写这样一个函数的最pythonic 的方法是什么?
You could do (assuming there are no duplicates):你可以这样做(假设没有重复):
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
This does not handle the case where any of the arguments aren't in the initial list.这不处理任何参数不在初始列表中的情况。
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
If you want to handle duplicates you can use something like this如果你想处理重复,你可以使用这样的东西
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.