-1

My requirement is to take 'arrList' string as an argument from main and split it using comma (,) and each name is an Array (arr1, arr2, arr3). Now all 3 arrays should be appended to a list. The output should be : list: 1,2,3,7,8,9,11,22,33. But should follow below steps only while implementing. Tried below code, but not able to convert. Any help is appreciated.

arr1 = [1,2,3]
arr2 = [7,8,9]
arr3 = [11,22,33]
list = []

def arrTest(arrList):
        var = arrList.split(',')
        for x in var:

    #f = open(, "r")
        #for x in f:
        #   list.append(x.rstrip('\n'))


if __name__ == '__main__':
    arrList = "arr1,arr2,arr3"
    arrTest(arrList)

3 Answers 3

1
arr1 = [1,2,3]
arr2 = [7,8,9]
arr3 = [11,22,33]
the_list = []

arrList = "arr1,arr2,arr3"
for array in arrList.split(','):
    if array in locals():
        the_list.extend(locals()[array])

print (the_list)

Output

[1, 2, 3, 7, 8, 9, 11, 22, 33]

locals() function returns a dictionary containing the variables defined in the local namespace.

1

You can use python dict data structure.

arr1 = [1,2,3]
arr2 = [7,8,9]
arr3 = [11,22,33]
d = {"arr1": arr1, "arr2": arr2, "arr3": arr3}

def arrTest(arrList):
    l = []
    var = arrList.split(',')
    for x in var:
        for e in d[x]:
            l.append(e)
    return l

if __name__ == '__main__':
    arrList = "arr1,arr2,arr3"
    l = arrTest(arrList)
    print(l)

Output

[1, 2, 3, 7, 8, 9, 11, 22, 33]
0

Use eval function

arr1 = [1,2,3]
arr2 = [7,8,9]
arr3 = [11,22,33]
out = []

def arrTest(arrList):
        list_strs = arrList.split(',')
        for list_str in list_strs:
          l = eval(list_str)
          out.extend(l)


arrList = "arr1,arr2,arr3"
arrTest(arrList)
print(out)

[1, 2, 3, 7, 8, 9, 11, 22, 33]

1
  • Thanks for the update, should follow above steps, but not this way.
    – RK.
    Commented May 10, 2019 at 10:25

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.