Python - Checking items in a list

Asked

Viewed 70 times

-2

I have a scenario, a little confused to explain... but I’ll try...

I need to compare listA with listaB, where case 1 or more items from listaA are within the listaB, I print it on the screen, but in case listaB have any items that are not on listaA, nothing happens.

The lists are similar to the ones below:

dns_svc = ['DNS', 's-udp-53', 's-tcp-53', 'junos-dns-udp', 'junos-dns-tcp']

app1 = ['s-tcp-443', 'Domain-logon']
app2 = ['s-tcp-443', 'DNS']
app3 = ['s-udp-53', 's-tcp-80']
app4 = ['DNS']
app5 = ['s-tdp-53', 's-udp-53']
app6 = ['junos-dns-udp', 'junos-dns-tcp']

dns_svc would be the listaA, while the lists appx are the listaB.

If anyone can make a suggestion.

I made the script below, but it’s bringing me more lines than it should. It should bring me 3 lines:

app1 = ['tcp-443', 'Domain-logon']
app2 = ['tcp-443', 'DNS']
app3 = ['udp-53', 'tcp-80']
app4 = ['DNS']
app5 = ['tcp-53', 's-udp-53']
app6 = ['junos-dns-udp', 'junos-dns-tcp']
applist = [app1, app2, app3, app4, app5, app6]

dns_svc = ['DNS', 's-udp-53', 's-tcp-53', 'junos-dns-udp', 'junos-dns-tcp']

for i in dns_svc:
    for a in applist:
        if i in a:
            print(i)
  • These items in the lists, they can be repeated within each list or are unique items within each list?

2 answers

1

A solution to print the unique data that is both in the list A and in the list B I used the set which is a collection of items where you cannot have duplicate values

Follows the code:

dns_svc = ['DNS', 's-udp-53', 's-tcp-53', 'junos-dns-udp', 'junos-dns-tcp']

app1 = ['tcp-443', 'Domain-logon']
app2 = ['tcp-443', 'DNS']
app3 = ['udp-53', 'tcp-80']
app4 = ['DNS']
app5 = ['tcp-53', 's-udp-53']
app6 = ['junos-dns-udp', 'junos-dns-tcp']
applist = [app1, app2, app3, app4, app5, app6]

items = set()

for i in dns_svc:
    for a in applist:
        if i in a:
            items.add(i)

for item in items:
    print(item)

the result after running the code:

junos-dns-udp
DNS
junos-dns-tcp
s-udp-53

-1

Kaique, thank you so much! I was trying here and I think I got tbm... But your suggestion seems to be much more efficient (to get still...), simpler and clearer :). Anyway follows as I did:

app1 = ['s-tcp-443', 'Domain-logon']
app2 = ['s-tcp-443', 'DNS']
app3 = ['s-udp-53', 's-tcp-80']
app4 = ['DNS']
app5 = ['s-tcp-53', 's-udp-53']
app6 = ['junos-dns-udp', 'junos-dns-tcp']
app7 = ['junos-dns-udp']
app8 = ['s-tcp-53', 'DNS']

def comparing(lst):
    dns_svc = ['DNS', 's-udp-53', 's-tcp-53', 'junos-dns-udp', 'junos-dns-tcp']
    flag = True
    for ap in lst:
        if ap not in dns_svc:
            flag = False
            continue
        else:
            if flag:
                flag = True

    return flag

applist = [app1, app2, app3, app4, app5, app6, app7, app8]

for app in applist:
    a = comparing(app)
    if a:
        print(app)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.