提问人:Kshtj 提问时间:11/17/2022 更新时间:11/17/2022 访问量:34
如何根据另一个列表的每个元素必须至少出现一次的条件对列表进行切片?
How to slice list based on a condition that every element of another list must appear atleast once?
问:
我有两个清单:
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]
但这只是检查最后一个元素是否在 .Idk 如何检查所有关键元素是否至少出现过一次。能帮上忙吗?a
key
答:
0赞
Faisal Nazik
11/17/2022
#1
此函数根据键的每个元素必须至少出现一次的条件对列表进行切片。
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]
0赞
Andrej Kesely
11/17/2022
#2
尝试:
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]
0赞
Kristian K
11/17/2022
#3
获得相同结果的另一种方法:)
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]
0赞
pho
11/17/2022
#4
这是一个有效的解决方案,它是 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}
接下来,在字典中查找列表中所有键的最大值。如果我们用来获取密钥,则将返回一个不存在的密钥,这将导致调用中的 TypeError。我们可以抓住这一点并适当地处理它。找到最大索引后,对列表进行切片,直到此索引以获取所需的内容。key
dict.get
None
max
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]
评论
key
a