我有兩個串列:
a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2, 1, 3, 5, 7, 0]
key = [1, 2, 4, 6]
我想檢查串列中的所有元素key是否至少一次出現在串列中a并洗掉之后的元素。
期望的輸出:
a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]
這是我試過的:
if a[-1] not in key:
indx = -1
while indx < 0:
if a[indx] in k:
ind = indx
indx = 1
else: indx= indx-1
a = a[:ind 1]
但這只是檢查的最后一個元素a是否在key. 如果所有關鍵元素至少出現一次,我不知道如何檢查條件。有什么幫助嗎?
uj5u.com熱心網友回復:
此函式根據鍵的每個元素必須在 a 中至少出現一次的條件對串列進行切片。
def slice_list(a, key):
for i in range(len(a)): # iterate over the list
if a[i] in key: # check if the element is in the key
key.remove(a[i]) # remove the element from the key
if not key: # if the key is empty
return a[: i 1] # return the sliced list
return a # if the key is not empty return the original list
print(slice_list(a, key))
Output: [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]
uj5u.com熱心網友回復:
嘗試:
a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2, 1, 3, 5, 7, 0]
key = [1, 2, 4, 6]
max_idx = max(a.index(k) for k in key)
print(a[: max_idx 1])
印刷:
[3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]
uj5u.com熱心網友回復:
獲得相同結果的另一種方法:)
for i in range(len(a)):
if all(x in a[:i] for x in key):
b = a[:i]
break
print(b)
Output: [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]
uj5u.com熱心網友回復:
這是一個 O(n) 的高效解決方案,不需要切片串列或list.index回圈中的操作:
首先,創建一個字典,將 的每個元素映射到它第一次出現a的索引。
a = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2, 1, 3, 5, 7, 0]
a_lookup = dict()
for ind, val in enumerate(a):
if val not in a_lookup:
a_lookup[val] = ind
這給了我們
a_lookup = {3: 0, 8: 1, 5: 2, 1: 3, 4: 4, 7: 5, 6: 8, 2: 10, 0: 15}
接下來,為串列中的所有鍵找到字典中的最大值key。如果我們使用dict.get獲取鍵,將回傳一個不存在的鍵None,這將導致max呼叫中出現 TypeError。我們可以抓住它并適當地處理它。一旦我們找到最大索引,將串列切片直到這個索引以獲得我們需要的東西。
key = [1, 2, 4, 6]
try:
max_index = max(a_lookup.get(k) for k in key)
sliced_list = a[:max_index 1]
except TypeError:
print("Error: all keys do not exist in a")
這使,
sliced_list = [3, 8, 5, 1, 4, 7, 1, 3, 6, 8, 2]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535236.html
上一篇:求分數n/1到1/n的總和
