简体   繁体   中英

Check if element exist in list

I'm new to python. I have two lists. The first one is ipaddress= [['10.25.16.201'], ['10.25.16.202'], ['10.25.16.203'], ['10.90.90.10']] and the second one is newipaddress =[["10.110.34.50"], ["10.25.17.212"], ["10.90.90.10"]]

How can I check ipaddress to verify if it contains an element from newipaddress ? This is what I've tried. Thanks in advance!

for x in ipAddress:
    print(x)
    for y in newipaddress:
        print(y)
        if (y in x):
            print(y)

We can avoid loops altogether and instead use a list comprehension:

ipaddress = [['10.25.16.201'], ['10.25.16.202'], ['10.25.16.203'], ['10.90.90.10']]
newipaddress = [["10.110.34.50"], ["10.25.17.212"], ["10.90.90.10"]]
output = [x in newipaddress for x in ipaddress]
print(output)  # [False, False, False, True]

To display the element in the first list, if it exist in the second list, use:

output = [x for x in ipaddress if x in newipaddress]
print(output)  # [['10.90.90.10']]

you can use 'if x in' to accomplish what you're after:

for x in ipaddress:
    if x in newipaddress:
        print('ip in newipaddress:', x)

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