删除python列表中的差异但保持顺序和重复项

2024-10-06 11:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

使用3.x版-想知道解决以下问题的最简单和本机方法:

示例列表:

listA = [1, 2, 3, 66, 0]
listB = [0, 0, 1, 2, 3, 66, 0, 99, 0, 3]

如何消除两个列表之间的差异,使新的listC以完全相同的顺序与listA相同?你知道吗

因此,使用上面的示例,listC应该等于[1, 2, 3, 66, 0]

列表A可能比列表B大,另一个条件是列表A永远不会有重复的数字,而列表B可能有重复的数字。你知道吗

我想解决的慈善俱乐部练习是:

林戴的脑部测试:

请写一个程序,打印'是',如果元素的B出现在a中的顺序,他们出现在B,但不一定连续。否则程序应打印“否”。你知道吗

林赛奖金测试:

请写一个程序,如果B的元素出现在 它们依次出现在B中。你知道吗

显然,如果有人喜欢这个挑战,那么请张贴完整的程序来解决这两个问题。你知道吗


Tags: 方法程序元素示例列表顺序数字差异
2条回答

另一种欺骗很小的方法是使用带有in运算符的字符串。如果将每个列表转换为一个字符串,则可以快速查看a是否是B的一个子串,顺序相同且连续。你知道吗

def aInB(listA, listB):
    str_a = "," + ",".join([str(c) for c in listA]) + ","
    # ',1,2,3,66,0,'
    str_b = "," + ",".join([str(c) for c in listB]) + ","
    # ',0,0,1,2,3,66,0,99,0,3,'

    return str_a in str_b
# True

只有当A的长度小于B时,这才有效,但根据问题的定义,这听起来总是正确的。额外的逗号是必要的,因为@stefanpochmann在评论中指出了问题。你知道吗

打印“是”和“否”非常简单:

if aInB(listA, listB):
   print("YES")
else:
   print("NO")

对于非连续方法,我相信您必须执行其中一种迭代方法。这个解决方案只是提供了一种思考is“A in B”的替代方法。你知道吗

编辑:我无法控制自己,所以这里有一个互动的方法,这可能是一种过度的方式,但也许你会发现它更容易理解(你永远不知道)。你知道吗

def aInB(listA, listB):
   # if listA is empty, don't even bother
   if not listA:
      return False

   # build a dictionary where each key is a character in listA
   # and the values are a list containing every index where that character
   # appears in listB
   occurences = {c:[i for i,e in enumerate(listB) if e==c] for c in listA}

   # now we are going to walk through listA again
   # but this time we are going to use our `occurences` dictionary
   # to verify that the elements appear in order
   last_index = 0
   for i,e in enumerate(listA):
     # if the character `e` never appears in listB
     # then it will have an empty list
     # and we can return False
     if not occurences[e]:
         return False

     # now the next possible index for the next character in listA
     # must be *greater* than the index of the last character we found
     # if no such index exists, then listA is not contained within listB
     # if it is, we update the last seen index
     next_possible_index = [x for x in occurences[e] if x > last_index]
     if not next_possible_index:
         return False
     last_index = next_possible_index[0]

   # if we make it out of the for loop
   # then all is well, and listA is contained in listB
   # but not necessarily consequtively 
   return True
def f(l1, l2):
    i1 = 0
    i2 = 0

    while i1 < len(l1) and i2 < len(l2):
        if l1[i1] == l2[i2]:
            i1 += 1
            i2 += 1
        else:
            i2 += 1

    if i1 == len(l1):
        return True
    return False

listA = [1, 2, 3, 66, 0]
listB = [0, 0, 1, 2, 3, 66, 0, 99, 0, 3]

print (f(listA, listB))
# will print true

相关问题 更多 >