簡體   English   中英

返回 6 元素或 3 元素元組列表的函數

[英]Function that returns a list of 6-element or 3-element tuples

我想編寫一個函數來比較兩個不同大小的list的每個3-tuple的 3 個元素。 具體來說,我想寫一個函數match如下:

list1 = ['a','b', 'a', 'a', 'c', 'a', 'c', 'c', 'a']; #just an example of a list1
list2 = ['c','a', 'a', 'c', 'a', 'a']; #just an example of a list2

def match(list1, list2, storage = []):
    for i in range(0, len(list1), 3):
       for j in range(0, len(list2), 3):
       #matching rule
          if (list1[i] == list2[j+1] and list1[i] == list2[j+2]) or (list1[i] == list2[j+1] and (list1[i] == list1[i+1] or list1[i] == list1[i+2])) or (list1[i] == list1[i+2] or (list1[i] == list1[i+1]) and (list2[j] == list2[j+1] or list2[j] == list2[j+2])) or (list2[j] == list1[i+1] and list2[j] == list1[i+2]):
             storage.append([list1[i], list1[i+1], list1[i+2], list2[j], list2[j+1], list2[j+2]])
         else: storage.append([list1[i], list1[i+1], list1[i+2]])
    return storage; #outside of the outer 'for' loop - obtain a list of all 6-element and/or 3-element tuples               

現在在獲得所有 3 元組對之后(例如,列表storage 1 個元素的形式為['a','b', 'a','c','a', 'a'] ),我想要獲取storage中包含['a', 'b', 'a']所有元素的索引作為 6 元素列表的一部分(例如['a','b', 'a','c','a', 'a'] ) 或 3 元素列表(例如['a','b', 'a'] )- storage僅有的兩種列表類型。

題。 誰能幫我驗證我的功能是否正確,然后是查找索引的部分? 我將不勝感激任何投入。

這可能會幫助您:

str1 = "abaacbabaacbabca" #...
l = []
l.append("caacaa")
l.append("ghijhg") # any 6 letter long string
l.append("acbaca")
for str2 in l:
    if any(str1[i:i+3] in str2 for i in range(len(str1)-3)):
        print(str2)

它返回(打印):

caacaa
acbaca

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM