Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果两个列表的最后一个元素在一个列表中为零,则收缩它们_Python - Fatal编程技术网

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

Python 如果两个列表的最后一个元素在一个列表中为零,则收缩它们,python,Python,我想要: 在: 输出: 我下面的代码运行正常,但我认为它看起来确实不是很好,可能有一种更简单的方法来解决这个问题: 在: 输出: 试一试 输出 [['b', '000'], ['d', 'efg']] 我的做法: 选择输入列表中的所有尾随零(在反向输入中) 计算上一步的尾随零 若并没有尾随的零,那个么就并没有任何内容可以连接,返回输入列表 如果有尾随零: 将两个列表拆分为两部分(尾随零的数量给出拆分点) 第一部分保持原样 第二部分是加入 所以你想要[a[0],''.join(a[1:]

我想要:
在:

输出:

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

输出:

试一试

输出

[['b', '000'], ['d', 'efg']]
我的做法:

  • 选择输入列表中的所有尾随零(在反向输入中)
  • 计算上一步的尾随零
若并没有尾随的零,那个么就并没有任何内容可以连接,返回输入列表

如果有尾随零:

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

所以你想要
[a[0],''.join(a[1:])]
?为什么要检查元素是否为
“0”
?这是不必要的还是我不明白你想做什么?这与标题中的“如果它们是零”有什么关系?我想我会删除我的,仔细看看ops解决方案,它肯定比这更复杂。这个现在看起来好多了+1
["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'])
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)