![](/img/trans.png)
[英]what is most pythonic way to find a element in a list that is different with other elements?
[英]Most pythonic way to find relation between two elements in a list
假設我有以下列表:
l = ["watermelon", "banana", "orange", "apple"]
我想編寫一個函數,該函數返回列表中另一個元素之前的元素。 例如:
>> is_before("banana", "watermelon")
>> False
>> is_before("banana", "apple")
>> True
編寫這樣一個函數的最pythonic 的方法是什么?
你可以這樣做(假設沒有重復):
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.