Creating Sublists from a “List”

前端 未结 5 2042
余生分开走
余生分开走 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)
    
    0 讨论(0)
  • 2021-01-24 09:05

    You can use zip to separate the list into two collections.

    x=[
    ['c4a2', '4534'], 
    ['2434', 'b375'],
    ['e750', 'c718']
    ]
    
    i,q = zip(*x)
    
    print i
    print q
    

    Result:

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

    These are tuples, though. If you really want lists, you would need to convert them.

    i,q = map(list, zip(*x))
    #or:
    i,q = [list(tup) for tup in zip(*x)]
    #or:
    i,q = zip(*x)
    i, q = list(i), list(q)
    
    0 讨论(0)
  • 2021-01-24 09:06
    #!/usr/bin/python
    import ast
    file = open("file.txt","r")
    
    i = list()
    q = list()
    
    for line in file:
        testarray = ast.literal_eval(line)
        q.append(testarray.pop())
        i.append(testarray.pop())
    
    print(i)
    print(q)
    

    something like that ?

    0 讨论(0)
  • 2021-01-24 09:16

    If you have read a list of lists, use zip() to turn columns into rows:

    file_result = [
        ['19df', 'b35d']
        ['fafa', 'bbaf']
        ['dce9', 'cf47']
    ]
    
    a, b = zip(*file_result)
    
    0 讨论(0)
  • 2021-01-24 09:22

    Taking for granted that you've already parsed the file:

    x = [['c4a2', '4534'], ['2434', 'b375'], ['e750', 'c718']]
    i = [a[0] for a in x] # ['c4a2', '2434', 'e750']
    q = [a[1] for a in x] # ['4534', 'b375', 'c718']
    

    This takes the first and second element of each sub-list, and puts it into a new variable.

    0 讨论(0)
提交回复
热议问题