简体   繁体   English

Python函数未按预期返回

[英]Python Function does not return as expected

I am trying to create a simple function to run through a while loop and append the entered IP addresses into a list for other uses. 我正在尝试创建一个简单的函数来运行while循环,并将输入的IP地址附加到列表中以供其他用途。 What I can see with my print statements is I only append to the list variable the IP most recently entered and the last print of the list returns a blank list. 我在print语句中看到的是,我只将最近输入的IP附加到列表变量,列表的最后一个打印返回一个空白列表。

def IP_Range():
    while True:
        ipLIST = []
        IP = raw_input('Please enter IP or Network, enter "end" to break: ')
        if IP == 'end':
            break
        else:
            ipLIST.append(IP)
            print ipLIST
    print ipLIST

IP_Range()

Thank you in advance I know this is really simple and I am overlooking something obvious. 提前谢谢我知道这很简单,我忽略了一些明显的东西。 As you can tell I am new to Python and programming in general. 正如你所知,我是Python和编程的新手。

At a glance, looks like you should put the list initialization outside the loop. 一目了然,看起来你应该把列表初始化放在循环之外 If you do ipLIST = [] inside the loop, then it will get reset to an empty list after every iteration. 如果你在循环中执行ipLIST = [] ,那么它将在每次迭代后重置为空列表。

def IP_Range():
    ipLIST = []
    while True:
        IP = raw_input('Please enter IP or Network, enter "end" to break: ')
        if IP == 'end':
            break
        else:
            ipLIST.append(IP)
            print ipLIST
    print ipLIST

IP_Range()

Result: 结果:

Please enter IP or Network, enter "end" to break: 123.45
['123.45']
Please enter IP or Network, enter "end" to break: 678.90
['123.45', '678.90']
Please enter IP or Network, enter "end" to break: 1.2.3.4
['123.45', '678.90', '1.2.3.4']
Please enter IP or Network, enter "end" to break: end
['123.45', '678.90', '1.2.3.4']

If you just want to collect a range of ips you can use iter and a list comp: 如果您只想收集一系列ips,可以使用iter和list comp:

def ip_range():
    return [ip for ip in iter(lambda:
        raw_input('Please enter IP or Network, enter "end" to break: '),"end")]

It will keep looping until "end" is the sentinel value is entered by the user. 它将保持循环,直到"end"是用户输入的标记值。

If you really want to print the ip's you can use a normal for loop: 如果你真的想要打印ip,你可以使用普通的for循环:

def ip_range():
    ips = [] # create outside the loop
    for ip in iter(lambda:
        raw_input('Please enter IP or Network, enter "end" to break: '), "end"):
        ips.append(ip)
        print(ip)
    print(ip)
    return ips

printing and returning are two very different things so if you want to use the list elsewhere make sure you return it, you should also use lowercase and underscores for variable names. 打印和返回是两个非常不同的东西,所以如果你想在其他地方使用列表确保你返回它,你也应该使用小写和下划线的变量名称。

problem is : loop every time initialize new empty list in while loop. 问题是:每次在while循环中初始化新的空列表时循环。 you can initialize list at outside of the while loop. 您可以在while循环外部初始化列表。 try to this : 尝试这个:

def IP_Range():
    ipLIST = []
    while True:
        IP = raw_input('Please enter IP or Network, enter "end" to break: ')
        if IP == 'end':
            break
        else:
            ipLIST.append(IP)
            IP = ""
            print ipLIST
    print ipLIST

IP_Range()

The solution proposed by Kevin is probably the best (it got my vote, it's the way I'd usually do it, and it would get my "Accept," if I were the OP). 凯文提出的解决方案可能是最好的(它得到了我的投票,这是我通常做的方式,如果我是OP,它会得到我的“接受”)。 However, if you've got a compelling reason that you absolutely must declare ipLIST inside your while loop (I can't think of one in this case, but that doesn't mean that you don't have one), then you can do it as follows: 但是,如果你有一个令人信服的理由,你绝对必须在你的while循环中声明ipLIST (在这种情况下我想不到一个,但这并不意味着你没有),那么你可以做到如下:

def IP_Range():
    while True:
        IP = raw_input('Please enter IP or Network, enter "end" to break: ')
        if IP == 'end':
            break
        else:
            try:
                ipLIST.append(IP)  # Append the IP to the list.
            except NameError:
                ipLIST = [IP,]  # Create the list, if it doesn't already exist.
            print ipLIST
    print ipLIST

IP_Range()

Results are: 结果是:

Please enter IP or Network, enter "end" to break: 1.2.3.4
['1.2.3.4']
Please enter IP or Network, enter "end" to break: 2.3.4.5
['1.2.3.4', '2.3.4.5']
Please enter IP or Network, enter "end" to break: 3.4.5.6
['1.2.3.4', '2.3.4.5', '3.4.5.6']
Please enter IP or Network, enter "end" to break: end
['1.2.3.4', '2.3.4.5', '3.4.5.6']
>>>

This works because, although you're creating the list inside the while loop (the try ... except ), you're not reinitializing it every time you go through the loop, as you did in your original code ( ipLIST = [] ). 这是有效的,因为虽然你在while循环中创建了列表( try ... except ),但是每次进行循环时都不会重新初始化它,就像你在原始代码中所做的那样( ipLIST = [] )。

I've done this from time to time when I've needed to avoid initializing an empty list , dict , or whatever. 当我需要避免初始化空listdict或其他任何内容时,我不时会这样做。 It's something you should have in your toolbox, just in case the need comes up. 这是你工具箱中应该有的东西,以防万一需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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