如果两个列表的最后一个元素在一个列表中为零,则收缩它们

2024-06-09 23:08:00 发布

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

我想要:
在:

["b","0","0","0"], ["d","e","f","g"]  

输出:

["b","000"], ["d","efg"]

我下面的代码运行正常,但我认为它看起来确实不是很好,可能有一种更简单的方法来解决这个问题:
在:

a=["b","0","0","0"]
c=["d","e","f","g"]

def contractsuffixes(reflex,root):
    laststringreflex=""
    laststringroot=""
    if reflex[-1]=="0":
        for i in reflex[::-1]:
            if i == "0":
                laststringreflex+=reflex[-1]
                laststringroot+=root[-1]
                reflex.pop()
                root.pop()
    elif root[-1]=="0":
        for i in root[::-1]:
            if i == "0":
                laststringreflex+=reflex[-1]
                laststringroot+=root[-1]
                reflex.pop()
                root.pop()
    if laststringreflex != "" and laststringroot != "":
        reflex.append(laststringreflex[::-1])
        root.append(laststringroot[::-1])
    
    return reflex,root
        
contractsuffixes(a,c)

输出:

(['b', '000'], ['d', 'efg'])

Tags: 方法inforifdefrootpopelif
2条回答

试一试

lists = [["b", "0", "0", "0"], ["d", "e", "f", "g"]]
out_lists = [[lst[0], ''.join(lst[1:])] for lst in lists]

print(out_lists)

输出

[['b', '000'], ['d', 'efg']]

我的做法:

  • 选择输入列表中的所有尾随零(在反向输入中)
  • 计算上一步的尾随零

若并没有尾随的零,那个么就并没有任何内容可以连接,返回输入列表

如果有尾随零:

  • 将两个列表拆分为两部分(尾随零的数量给出拆分点)
  • 第一部分保持原样
  • 第二部分是加入
from itertools import takewhile

a = ["b", "0", "0", "0"]
b = ["d", "e", "f", "g"]

zeroes = list(takewhile(lambda x: x is "0", reversed(a)))

lenZeroes = len(list(zeroes))
a1 = a[:-lenZeroes] + [''.join(zeroes)] if lenZeroes > 0 else a
b1 = b[:-lenZeroes] + [''.join(b[-lenZeroes:])] if lenZeroes > 0 else b
print(a1)
print(b1)

相关问题 更多 >