簡體   English   中英

Python 當在另一個列表中找到一個列表的元素時向列表添加新值的代碼

[英]Python code that adds a new value to the list when it finds the elements of one list in another list

L1 =['0-0-3-0-0-80-0', '0-0-3-0-0-82-0']

L2 = [['0', '4', '0', '0', '42', '71','42','0-0-0-0-0-4-0'],['0', '4', '2', '0', '42', '72','42', '0-0-0-1-0-4-2'],['0', '80', '0', '0', '42', '81','43', '0-0-3-0-0-80-0'],['0', '80', '0', '1', '21', '81','43', '0-0-3-0-0-80-0'],['0', '81', '0', '0', '43', '82', '21', '0-0-3-1-0-81-0',],['0', '82', '0', '0', '21', '83', '43', '0-0-3-0-0-82-0']]

所以如果代碼找到值,我想在 L2 列表中搜索 L1 的值

'0-0-3-0-0-80-0' is in ['0', '80', '0', '0', '42', '81','43', '0-0-3-0-0-80-0'] and ['0', '80', '0', '1', '21', '81','43', '0-0-3-0-0-80-0']

and

'0-0-3-0-0-82-0' is in ['0', '82', '0', '0', '21', '83', '43', '0-0-3-0-0-82-0']

最后的結果會這樣顯示

L2 = [['0', '4', '0', '0', '42', '71','42','0-0-0-0-0-4-0',""],['0', '4', '2', '0', '42', '72','42', '0-0-0-1-0-4-2',""],['0', '80', '0', '0', '42', '81','43', '0-0-3-0-0-80-0',"found"],['0', '80', '0', '1', '21', '81','43', '0-0-3-0-0-80-0',"found"],['0', '81', '0', '0', '43', '82', '21', '0-0-3-1-0-81-0',],['0', '82', '0', '0', '21', '83', '43', '0-0-3-0-0-82-0',"found"]]

for i in range(0,len(L2)):
    for x in L1:
        if x in L2[i]:
           result.append(L2[i]+["found"])
       else:
           result.append(L2[i]+[""])

我試過了,但結果重復了兩次。

該代碼創建了兩次結果。

聽起來您想 append "found"""L2中的每個列表。

下面的代碼默認附加"" ,並在每次找到東西時用"found"覆蓋它。 不需要result變量:

for i in range(0,len(L2)):
    if len(L2[i]) == 8:
        L2[i].append('')
    for x in L1:
        if x in L2[i]:
            L2[i][8] = 'found'

Output 按要求

暫無
暫無

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

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