Search code examples
arrayspython-3.xstdin

How to convert input stdin to list data structure in python


I have a stdin data in this format:
100
85 92
292 42
88 33
500
350 36
800 45
0

I want something like this [[100, [85, 92], [292, 42], [88, 33]], [500, [350, 36], [800, 45], [0]]


Solution

  • Something like the following (I have tested) should do it:

    lst = []
    sublst = []
    for line in sys.stdin:
        lineLst = [int(x) for x in line.split()]
        if len(lineLst) == 1:
            if sublst: lst.append(sublst)
            sublst = lineLst
        else:
            sublst.append(lineLst)
        
    if sublst[0] == 0: lst.append(sublst)