![](/img/trans.png)
[英]Finding if any element in a list is in another list and return the first element found
[英]Finding the index of the first element of a list in another list
main_list = ['4', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
my_list = ['4', '5', '6']
我的問題是,如何在main_list中找到my_list的索引?
my_list中的整數在main_list中必須連續。
我嘗試使用main_list.index(my_list[0])
但如果特定元素中有多個元素,它將返回錯誤的索引號。 我需要得到的結果是4,但是使用main_list.index(my_list[0])
它只會給出0作為其索引。
如果需要澄清,我可以編輯該帖子並提供其他詳細信息。 抱歉,英語不是我的母語。
試試這個
for i in range(len(main_list)-len(my_list)):
if main_list[i:i+len(my_list)] == my_list:
index = i
break
這應該適用於列表中所有可能的類型。
您可以使用join()
函數將兩個列表都轉換為字符串,然后反復比較字符串以找到匹配項。
編輯:對它進行了更改兩個數字位數的工作。 還添加了一個浮子盒。
例如:
main_list = ['4', '1', '2', '3', '40.1', '52', '61', '7', '8', '9', '10']
my_list = ['40.1', '52', '61']
index = -1
for i in range(len(main_list)):
if '#'.join(main_list[i:i+len(my_list)]) == '#'.join(my_list):
index = i
break
print(index)
如果您想要一種算法解決方案:
def Find(haystack, needle):
n, h = len(needle), len(haystack)
assert n <= h
for i in range(h):
if h - i <= n: break
count = 0
for i_, j in zip(range(i, i + n), range(n)):
if haystack[i_] == needle[j]:
count += 1
if count == n: return i
return -1
一種更有效的襯墊:
print ','.join(main_list).find(','.join(my_list)) - ''.join(main_list).find(''.join(my_list))
將它們轉換為帶有用逗號分隔的元素的字符串,找到出現的位置,然后減去當逗號不存在時找到的出現位置,並且您有答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.