Creating Sublists from a “List”

前端 未结 5 2044
余生分开走
余生分开走 2021-01-24 08:21

I have a list in a file, looks like this

c4a24534,2434b375,e750c718, .... 

I have split at \",\" and brought the below list.

x         


        
5条回答
  •  孤城傲影
    2021-01-24 09:01

    Assuming this is a contents of input.txt file:

    c4a24534,2434b375,e750c718
    

    Use zip() for splitting into two lists:

    with open('input.txt') as f:
        i, q = zip(*((x[:4], x[4:]) for line in f for x in line.split(',')))
    
    print i
    print q
    

    Prints:

    ('c4a2', '2434', 'e750')
    ('4534', 'b375', 'c718')
    

    These are tuples, if you need to make lists from them, call list() on each:

    print list(i)
    print list(q)
    

提交回复
热议问题