简体   繁体   中英

Remove items from a list of tuples based on multiple conditions

I have a list of tuples of different sizes. I want to iterate over each tuple and remove value from the tuple if the previous value is three digit number.

For example:


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

I need to get a list in that form:


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

I think simple loop with if-else condition will do the work

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM