Home > Blockchain >  Specifically point to a list in a for loop
Specifically point to a list in a for loop

Time:12-15

I have a class called Config with an object called "ip_list". There are two lists called ip_list1 and ip_list2. What I want to do is iterate though one of the ip lists based on a user selection. A simple version of my code is here:

ip_list1 = ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4']
ip_list2 = ['192.168.1.5', '192.168.1.6', '192.168.1.7', '192.168.1.8']

class Config: 
    def __init__(self):
        self.ip_list = ""

list = int(input("Chose ip list: ")

if list == 1:
    Config.ip_list = "ip_list1"
elif list == 2:
    Config.ip_list = "ip_list2"
else:
    print(f"{list} is an invalid choice")

for ip in Config.ip_list:
    <do something>

This obviously doesn't work or I wouldn't be asking the question :) It iterates through each letter of the actual string "ip_listx". How do I get it to point to the list and not just use the string?

CodePudding user response:

You have a few issues with the code:

  1. list is a data structure in python. Try renaming the variable from list to something else like foo.
  2. You're using int() to handle taking an input but there's a syntax error because you forgot to include the trailing bracket for int(). It should be foo = int(input("Choose ip list: ")). Sample:
ip_list1 = ['192.168.1.1', '192.168.1.2', '192.168.1.3', '192.168.1.4']
ip_list2 = ['192.168.1.5', '192.168.1.6', '192.168.1.7', '192.168.1.8']

class Config: 
    def __init__(self):
        self.ip_list = ""

foo = int(input("Chose ip list: "))

if foo == 1:
    Config.ip_list = "ip_list1"
elif foo == 2:
    Config.ip_list = "ip_list2"
else:
    print(f"{foo} is an invalid choice")

for ip in Config.ip_list:
    print(ip)

if __name__ == "__main__":
    c = Config()

CodePudding user response:

c-z answered the question in the comments...

You set it to the string and not the list, did you mean Config.ip_list = ip_list1 rather than Config.ip_list = "ip_list1"?

  • Related