簡體   English   中英

通過在python中比較兩個嵌套列表來生成0和1的嵌套列表

[英]Generate a nested list of 0's and 1's by comparing two nested lists in python

我有兩個嵌套列表,如下所示:

list_x = [[21, 58, 68, 220, 266, 386, 408, 505, 518, 579], 
          [283, 286, 291, 321, 323, 372, 378, 484, 586, 629]]

list_y = [[21, 220, 386, 505, 518], [286, 291, 321, 323, 372]]

我想比較在上述嵌套列表意思相同的索引位置的元件list_x[0]應該進行比較list_y[0]等。

我想生成第三(嵌套)列表,以便對於list_x[0]每個數字,如果該數字也在list_y[0] ,則生成一個,如果不匹配,則生成零。 應該對list_x[1]list_y[1]執行相同的過程。

我的嵌套輸出列表中每個子列表的長度應為10(即,較長子列表的長度,一個為匹配項,一個為零,否則為零)。 所有子列表均按升序排序。

一些額外的信息價值共享是list_y[0]list_y[1]是子集list_x[0]list_x[1]分別。

因此,我要搜索的輸出列表如下:

out = [[1,0,0,1,0,1,0,1,1,0], [0,1,1,1,1,1,0,0,0,0]]

我嘗試了以下代碼,但又得到了10個額外的零

list_x = [y for x in list_x for y in x] #to flatten list_x

result = []
for y in list_y:
    sublist = []
    for x in list_x:
        if x in y:
            sublist.append(1)
        else: 
            sublist.append(0)
    result.append(sublist)

上面的代碼為我提供了以下內容:

result = [[1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0]]

謝謝您的幫助!

我們可以使用zip並發地遍歷子列表,然后執行in check,例如:

[[int(x in suby) for x in subx] for subx, suby in zip(list_x, map(set, list_y))]

然后產生:

>>> [[int(x in suby) for x in subx] for subx, suby in zip(list_x, list_y)]
[[1, 0, 0, 1, 0, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0]]

map(set, list_y)被用於映射的所有子列表list_y在套中,由於用於一組通常為O運行的查找(1),而在一個列表中查找需要O(N)。

托馬斯,歡迎您!

嘗試這個:

#!/usr/bin/env python2

list_x = [[21, 58, 68, 220, 266, 386, 408, 505, 518, 579],
          [283, 286, 291, 321, 323, 372, 378, 484, 586, 629]]

list_y = [[21, 220, 386, 505, 518], [286, 291, 321, 323, 372]]

answer=[]
for ( index, inner_list ) in enumerate( list_x ):
  answer.append([])

  for ( inner_index, inner_value ) in enumerate(inner_list):
    answer[index].append(0)
    if inner_value in list_y[ index ]:
      answer[index][inner_index] = 1
print answer

試試看...您將獲得輸出

    list_x = [[21, 58, 68, 220, 266, 386, 408, 505, 518, 579], 
      [283, 286, 291, 321, 323, 372, 378, 484, 586, 629]]

    list_y = [[21, 220, 386, 505, 518], [286, 291, 321, 323, 372]]
    result =[]
    for ind,lst in enumerate(list_x):
        sublist  =[]
        for ele in lst:
            if ele in list_y[ind]:
                sublist .append(1)
            else:
                sublist .append(0)
         result.append(sublist )
    print(result)

產量

    [[1,0,0,1,0,1,0,1,1,0], [0,1,1,1,1,1,0,0,0,0]]

暫無
暫無

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

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