如果同一索引处的值相等,则删除两个列表的尾随项

问题描述 投票:1回答:3

我想完成以下任务:

我有两个列表ab,保证大小为5.我现在想要从两个列表的末尾删除相同索引/压缩/转置时相同的值。作为输入和预期输出的示例:

In:   a=[2,3,2,2,1], b=[2,3,4,1,1]
Out:  a=[2,3,2,2],   b=[2,3,4,1]

In:   a=[9,10,10,10,10], b=[10,10,10,10,10]
Out:  a=[9],             b=[10]

In:   a=[1,2,3,4,5], b=[1,2,3,4,5]
Out:  a=[],          b=[] 
# (a=[1], b=[1] or a=[1,2,3,4,5], b[1,2,3,4,5] are fine as well
#  for this last example, as long as there isn't any error)

In:  a=[10,10,10,10,10], b=[10,10,10,10,9]
Out: a=[10,10,10,10,10], b=[10,10,10,10,9]

我知道如何删除在相同索引处相同的所有值:

f = lambda a,b: [] if a==b else map(list, zip(*[(i,j) for(i,j) in zip(a,b) if i!=j]))[0]

我可以称之为:

a,b = [2,3,2,2,1], [2,3,4,1,1]
A,B = f(a,b), f(b,a)

但这会导致A=[2,2], B=[4,1],也取消领先的价值观。

在同一索引中找到不匹配之前,从两个列表中删除尾随值的最简单方法是什么? PS:这是针对code-golf的挑战。我几乎从不在Python中编程,但如果我在其他地方使用它,我可能会为拉链创建变量,而不是我上面提到的这个非常难以理解的单行。尽管如此,对于这个答案,我宁愿尽可能简短地回答可读性,尽管这不是这个问题的要求。只是想知道如何完成它。

python python-2.x transpose equality trailing
3个回答
3
投票

一种方法是使用生成器表达式从末尾开始迭代两个列表,并保持第一个索引找到匹配项:

a=[2,3,2,2,1]
b=[2,3,4,1,1]

ix = next((ix for ix,(i,j) in enumerate(zip(a[::-1],b[::-1])) if i != j), None) 

然后您可以使用它来切片列表(使用if语句检查返回的值是否为None,这意味着两个列表相等):

if ix:
    print(a[:len(a)-ix])
    print(b[:len(b)-ix])
# [2, 3, 2, 2]
# [2, 3, 4, 1]

而对于你的另一个例子:

a=[9,10,10,10,10]
b=[10,10,10,10,10]

ix = next(ix for ix,(i,j) in enumerate(zip(a[::-1],b[::-1])) if i != j)

if ix:
    print(a[:len(a)-ix])
    print(b[:len(b)-ix])
# [9]
# [10]

2
投票
a=[2,3,2,2,1]
b=[2,3,4,1,1]

解决方案1:使用while循环

注意:异常处理(try-except块),以避免:IndexError:列表索引超出范围,在特殊情况下,如果你有一个= [1,2,3,4,5],b = [1,2, 3,4,5]

try: 
    while a[-1] == b[-1]:
            a.pop()
            b.pop()
except:
    pass
print (a)
print (b)

要么

while a and a[-1] == b[-1]:
        a.pop()
        b.pop()

print (a)
print (b)

结果:

in: a=[2,3,2,2,1], b=[2,3,4,1,1]
out: [2, 3, 2, 2],[2, 3, 4, 1]

in: a=[10,10,10,10,10],b=[10,10,10,10,9]
out: [10, 10, 10, 10, 10],[10, 10, 10, 10, 9]

in: a=[9,10,10,10,10],b=[10,10,10,10,10]
out: [9],[10]

in: a=[1,2,3,4,5],b=[1,2,3,4,5]
out: [], []

解决方案2:使用递归

def remove(a,b):
    if a[-1] == b[-1]:
        a.pop()
        b.pop()
        return remove(a,b)
    # else:
    #     return

remove(a,b)
print (a)
print (b)

Python切片()

slice()构造函数创建一个切片对象,表示由range(start,stop,step)指定的索引集。

 a[-1] # return a last element of list

Python列表pop()

pop()方法从列表中删除给定索引处的项目。该方法还返回已删除的项目。

pop()方法的语法是:

list.pop(index)

a.pop() # removing last element of list

0
投票

您可以迭代与原始文件相反的列表副本,然后遍历副本并从原始文件中删除元素,如此函数:

class SomeClass:

def removeSameCharacters(a, b):
    x = a.reverse
    y = b.reverse

    for i in x:
        if x[i] == y[i]:
            a.remove[i]
            b.remove[i]
        else:
            break
© www.soinside.com 2019 - 2024. All rights reserved.