根据多个条件从元组列表中删除项



我有一个不同大小的元组列表。我想遍历每个元组,如果前一个值是三位数,则从元组中删除值。

例如:


ls = [(1, 1, 1, 2, 3), (1, 2, 2), (222, 234, 250, 10), ...]

我需要以这种形式得到一个列表:


ls1 = [(1, 1, 1, 2, 3), (1, 2, 2), (222, 234, 250), ...]

我认为简单的循环加上if-else条件就可以了

ls = [(1, 1, 1, 2, 3), (1, 2, 2), (222, 234, 250, 10)]
three_digit_seen = False
output = []
for i in ls:
three_digit_seen = False
temp = []
for j in i:
if(len(str(j)) == 3):
three_digit_seen = True
if(three_digit_seen and (len(str(j)) != 3)):
continue
temp.append(j)

output.append(tuple(temp.copy()))

print(output)
[(1, 1, 1, 2, 3), (1, 2, 2), (222, 234, 250)]

最新更新