简体   繁体   中英

second return value from first function is printing twice

I am attempting to simply print out the values(ports) that I have appended to their respective lists. I am separating this by tcp and udp. My dictionary that I am passing to _does_port_dict_have_type looks like this {'22': 'TCP', '53': 'UDP', '31337': 'TCP', '80': 'TCP', '515': 'UDP'}

Here is my code

x = _expected_ports_type_to_dict(ET.parse('scanme.nmap.org.xml'))


TCP_LIST = []
UDP_LIST = []


def _does_port_dict_have_type(port_dict):
    for port, typee in port_dict.iteritems():
         if (typee is not None) and len(typee) > 0:
             if typee == "TCP":
                 TCP_LIST.append(port)
             else:
                 UDP_LIST.append(port)
        else:
            pass
    return ','.join(UDP_LIST), ','.join(TCP_LIST)


UDP = _does_port_dict_have_type(x)[0]
TCP = _does_port_dict_have_type(x)[1]


def print_value(func):
    print func


print_value(UDP)
print_value(TCP)

Here is my output 80,31337,22 515,53,515,53

The TCP variable or the [1] position of _does_port_dict_have_type() is the value that always shows up twice. It doesn't matter if I pass it UDP_LIST or TCP_LIST. Does anyone have any ideas to why this may be happening?

Actually, you're calling the function twice here:

UDP = _does_port_dict_have_type(x)[0]
TCP = _does_port_dict_have_type(x)[1]

Since the function returns a tuple, there's no need to call it twice. You can use tuple unpacking and assign both return values in a single statement like:

UDP, TCP = _does_port_dict_have_type(x)

And your function can be greatly simplified with comprehension:

def _does_port_dict_have_type(port_dict):
    tcp = [k for k,v in port_dict.items() if v == "TCP"]
    udp = [k for k,v in port_dict.items() if v == "UDP"]
    return ','.join(udp), ','.join(tcp)

In python 2, which it looks like you're using iteritems instead of items

def _does_port_dict_have_type(port_dict):
    tcp = [k for k,v in port_dict.iteritems() if v == "TCP"]
    udp = [k for k,v in port_dict.iteritems() if v == "UDP"]
    return ','.join(udp), ','.join(tcp)

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