我的代码出了什么问题?有更好的方法吗?

What went wrong with my code?Is there a better way to do this?

所以我得到了这个列表

integer_data=[[2, 3, 4, 5], [1, 2, 3, 6], [1, 3, 6], [0, 1, 5, 6], [1, 2, 3, 4]]

我得到了另一个列表列表

adjList=[[1, 0], [0, 2, 3, 1], [1, 3, 4, 5, 2], [1, 2, 4, 5, 3], [2, 3, 5, 6, 4], [2, 3, 4, 6, 5], [4, 5, 6]]

和一个空列表

listPrint=[]

我想取 integer_data 每个列表中的第一个数字;例如no.2 然后在 adjList 中找到最后一个数字与该数字匹配的列表(在本例中为 no.2),即列表 [1, 3, 4, 5, 2]。如果列表中有项目 integer_data 不在 [1, 3, 4, 5, 2] 中,然后我将 'No' 附加到 listPrint,否则我附加 'Yes'。然后我转到 [=31= 中的下一个列表] 并重复。

adjList中每个列表的最后一个数字是unique.The输出应该是

resultList=['Yes','No','No','No','No','No']

我尝试使用此代码,结果很差 off.I 我是 Python 的新手,因此我们将不胜感激。

for item in integer_data:
itemToCheck=item[0]
 for itemTwo in adjList:
    itemTwoToCheck=itemTwo[-1]
    if itemToCheck==itemTwoToCheck:
        itemToCompareOne=item
        itemToCompareTwo=itemTwo
        for itemThree in itemToCompareOne:
            if itemThree not in itemToCompareTwo:
                listPrint.append('No')
            else:
                listPrint.append('Yes')

这是一道独立于编程语言的纯算法题。

以下方法可以帮助您高效地完成它:

  1. 复制integer_data中所有列表的第一个元素(以相同的顺序)。说 first_elem_list
  2. 复制 adjList 中所有列表的最后一个元素(以相同的顺序)。说 last_elem_list
  3. 现在,检查所有索引(位置)first_elem_list 成员在 last_elem_list
  4. 中有哪些匹配项(即相同的值)
  5. 如果匹配,则检查问题中是否存在数字。如果不是,直接在输出列表中标记 "no"。

希望这种方法能进一步分解:)

让我们通过您的示例进行操作。根据您的描述,我假设预期的答案是 ['yes', 'no', 'no', 'no', 'no'],因为 integer_data.

中只有 5 个列表

此外,为了简洁起见,我将这两个列表重命名为 AB

A=[[2, 3, 4, 5], [1, 2, 3, 6], [1, 3, 6], [0, 1, 5, 6], [1, 2, 3, 4]]
B=[[1, 0], [0, 2, 3, 1], [1, 3, 4, 5, 2], [1, 2, 4, 5, 3], [2, 3, 5, 6, 4], [2, 3, 4, 6, 5], [4, 5, 6]]
listPrint=[]

# Construct dictionary d. 
# For every list in B, map its last element to the list itself
d={}
for list_b in B:
    d[list_b[-1]] = list_b

'''
In your example, d is
{   0: [1, 0],
    1: [0, 2, 3, 1],
    2: [1, 3, 4, 5, 2],
    3: [1, 2, 4, 5, 3],
    4: [2, 3, 5, 6, 4],
    5: [2, 3, 4, 6, 5],
    6: [4, 5, 6]
}
'''

for list_a in A:
    list_b = d[list_a[0]] # find the corresponding list_b
    answer = 'yes'
    for a in list_a:
        if a not in list_b:
            answer = 'no'
            break
    listPrint.append(answer)

print(listPrint) # ['yes', 'no', 'no', 'no', 'no']

列表理解是 python循环列表中的项目并根据对输入列表元素的操作创建新列表的巧妙方法

alast = [e[-1] for e in adjList]

['Yes' if (d[0] in alast) and
          set(d).issubset(adjList[alast.index(d[0])])
       else 'No'
 for d in integer_data]

['Yes', 'No', 'No', 'No', 'No']  

第一个 listcomp 列出 adjList

的每个子列表 e 中的最后一个数字 e[-1]

第二个块实际上是一个列表理解(添加了换行符),它从最后一行的 integer_data 中获取子列表 dfor d in integer_data

第 3 行的内联 if-else 根据第 1 行和第 2 行之间的逻辑拆分给出 'Yes''No'

第一行逻辑(d[0] in alast)很明显

逻辑表达式“and-ed”的第 2 行与第 1 行检查 d 中的所有数字是否都在 [= 的匹配索引 alast.index(d[0]) 子列表中13=] 使用 python 的 set 内置对象的 .issubset() 方法逻辑