【发布时间】:2022-01-24 04:47:52
【问题描述】:
我目前正在尝试构建 python 代码,以在三个列表的长度不相等的情况下删除列表中的最后一个元素。这样可以节省返回列表并在每次不满足条件时手动 listExample{}.pop() 到某些列表的时间。
最小长度的列表应该是所有三个列表所需的元素长度。在此示例中,它将是四个元素,但理想情况下,程序应计算三个列表的长度并获取最小的整数作为目标。如果列表不相等,则程序将从正确的列表中 .pop() 直到满足 listLength1 == listLength2 == listLength3。
以下是我为设置示例而创建的列表和变量:
listExample1 = ['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement', 'FifthElement', 'SixthElement']
listExample2 = ['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
listExample3 = ['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement', 'FifthElement']
listLength1 = len(listExample1)
listLength2 = len(listExample2)
listLength3 = len(listExample3)
print(listLength1) #6
print(listLength2) #4
print(listLength3) #5
这是我目前正在构建的代码:
if listLength1 == listLength2 == listLength3:
pass
elif listLength1 < listLength2:
pass
elif listLength1 > listLength3:
pass
elif listLength1 == listLength2:
pass
elif listLength2 < listLength1:
pass
elif listLength2 > listLength3:
pass
elif listLength2 == listLength1:
pass
elif listLength3 < listLength3:
pass
elif listLength3 > listLength1:
pass
elif listLength3 == listLength2:
pass
else:
pass
if/elif 似乎是多余的,当我在某种情况下启动 listExample1.pop() 时,我觉得有出错的余地,这可能会搞砸。解决这个问题的最佳方法是什么?
期望的输出:
print(listExample1) #['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
print(listExample2) #['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
print(listExample3) #['FirstElement', 'SecondElement', 'ThirdElement', 'ForthElement']
【问题讨论】:
-
minLength = min(listLength1, listLength2, listLength3),后跟三个while len(listExample1) > minLength: listExample1.pop()形式的循环。您不必为最短的列表做任何特别的事情,它的循环不会做任何事情。 -
你为什么要用pops来做这个?这似乎不是正确的工具。
-
从列表中删除最后一个元素不会在开始时倾斜数据是pop的想法
-
这里会更好地使用切片方法吗?例如获取最小列表长度并将其存储为 n。从那时起,您可以剪切所有列表,直到 n 像 "listExample1 = listExample1[:n]"
-
@bbsmfb 我的意思是为什么要使用 pop 来实现这一点,而不是
del(现在已经回答了)。