Check contain string, and move the rest element to new list

I have a question related to a specific string being moved to new list.
IF I have list like [“hello”, “world”, “====”,“my”, “name”,“is”,“XXX”],
After “====”, the rest of the element will append to a new list

so there are two new lists,
listnew1 will store => [‘hello’, ‘world’]
listnew2 will store =>[‘my’, ‘name’, ‘is’, ‘XXX’]

How am I able to accomplish it, I have no idea, please help me. Thanks

lista= ["hello", "world", "====","my", "name","is","XXX"]

listnew1= []
listnew2=[]
for i in lista:
    if "=" not in i:
        listnew1.append(i)
    else:
        listnew2.append(i)
print(listnew1)
print(listnew2)

rightnow the output is:

[‘hello’, ‘world’, ‘my’, ‘name’, ‘is’, ‘XXX’]
[‘====’]

but i iwish to be like this

[‘hello’, ‘world’]
[‘my’, ‘name’, ‘is’, ‘XXX’]

Well, to fix your approach, the simplest way would be to use a boolean flag to determine if you’re before or after the "====", and use that to pick which list you’re appending to. Something like:

before = True

for val in lista:
    if val == "====":
        before = False
        continue # to avoid adding the separator itself
    elif before:
        listnew1.append(val)
    else:
        listnew2.append(val)

The reason your way doesn’t work is that values like "XXX" don’t themselves contain "=", so everything besides your separator value passes your if’s condition.

But a better way would be to just use the index method to find your separator, and then slice the list into the two pieces you want. Something like:

def partition_list(values, separator):
    pos = values.index(separator)
    return values[:pos], values[pos + 1:]

lista = ["hello", "world", "====","my", "name","is","XXX"]

listnew1, listnew2 = partition_list(lista, "====")
2 Likes

Thanks a lot , let me study it.

HI ,
sorry I still have some problem.
if my text file looks like this:
=========================UL=========================
20230204.142918.219783 40.156700 40.072029
20230204.142923.237399 40.176239 40.091530
20230204.142928.254972 40.160927 40.076252
=========================DL=========================
20230204.142442.270222 0.000000 0.000000
20230204.142447.287388 0.000000 0.000000
20230204.142452.304622 0.000000 0.000000
20230204.142457.321808 0.000000 0.000000

How am I able to let under UL save in listnew1, and under DL save to listnew2?
I try like this it seems not to work

before = True 
listnew1=[]
listnew2=[]
with open ('result.txt', 'r')as myfile:  
    readline=myfile.read().splitlines()
    for val in readline:
        if "====" in val:
            before = False
            continue # to avoid adding the separator itself
        elif before:
            listnew1.append(val)
        else:
            listnew2.append(val)

print("="*40)

print(listnew1)
print("="*40)
print(listnew2)

But it only saves to listnew2 list. Is there any way to save it to a separate list?

That format is hardly what you described before, but anyway, my suggestion would be to use a dictionary to hold your different lists. Something like:

lists = {}
current_key = None

for line in lines:
    if "=" in line:
        current_key = line.strip("=")
        lists[current_key] = []
    else:
        assert current_key is not None # there shouldn't be data before a header
        lists[current_key].append(line)

print(lists["UL"])

print(lists["DL"])
1 Like

Hi Kevin,
sorry to bother you again. I have one last question to ask an easy one.

From the above code, how to check files containing UL, DL or both UL and DL.

So what I wants is if my file contains ONLY UL, then types="UL", if ONLY DL then types="DL", if contain both UL and DL , types = "both".

Is there any method to determine it contain only UL, DL or both. Right now If my file contains both UL and DL, it will always return DL.

types = "none"
for i in lists:
    #print(i)
    if "UL" in i:
        types="UL"
        print("UL")
        
    elif "DL" in i:
        types="DL"
        print("DL")
    elif  "UL" in i and "DL" in i:
        types="both"
        print("both UL DL")

print("==========")
print(types)

Keep in mind that if you have a chain of conditions using if and elifs, it stops looking after finding the first condition that evaluates to True. The later conditions may or may not also evaluate to True, but that doesn’t matter; they won’t get checked, and their bodies won’t run even if they would’ve evaluated to True.

For situations like this where multiple conditions can be true, you should put the more specific case on top. This ensures it will be checked first. In other words, instead of:

if foo:
    ...
elif bar:
    ...
elif foo and bar:
    ...

you should do:

if foo and bar:
    ...
elif foo:
    ...
elif bar:
    ...

I don’t get it my file does not exist DL but why when i use print("DL" and "UL" in lists) it prints True. Do you have any idea why is it?

Shouldn’t it be False, since I use AND, when both exist should be TRUE. But in my list only occur one condition.
Do you know what’s the reason? Thanks

code:

print(lists)
print("DL" and "UL" in lists) #True
print("UL" in lists) #True
print("DL" in lists) #False
'''
if "DL" and "UL" in lists:
    print("both UL and DL exist")
elif "UL" in lists:
    print("UL exist")
elif "DL" in lists:
    print("DL exisit")
'''

output:

{'UL': ['datettime ingress-traffic egress-traffic ', '20230208.181737.034128 0.000000 0.000000 ', '20230208.181742.051501 0.000000 0.000000 ', '20230208.181747.068881 0.000121 0.000116 ', '20230208.181752.086879 0.000563 0.000540 ']}
True
True
False

In interactive interpreter type help('and') which provides useful information:

The expression “x and y” first evaluates x; if x is false, its
value is returned; otherwise, y is evaluated and the resulting value
is returned.

Knowledge about Truth Value Testing is also handy.

1 Like

The correct logic is if "DL" in lists and "UL" in lists:

print("DL" in lists and "UL" in lists)
print("UL" in lists)
print("DL" in lists)

if "DL" in lists and "UL" in lists:
    print("both UL and DL exist")
elif "UL" in lists:
    print("UL exist")
elif "DL" in lists:
    print("DL exist")
else:
    print("Neither exist")
1 Like

Thanks work prefect

1 Like

thanks for sharing AND concept