Storing and updating lists in Python dictionaries: why does this happen?

前端 未结 4 1657
一向
一向 2021-01-30 22:19

I have a list of data that looks like the following:

// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8

... and

4条回答
  •  忘掉有多难
    2021-01-30 23:08

    In the case your data is not already sorted by desired criteria, here's the code that might help to group the data:

    #!/usr/bin/env python
    """
    $ cat data_shuffled.txt
    0,2,7
    1,4,7
    0,4,7
    1,9,0
    1,2,5
    0,6,7
    1,6,8
    0,9,5
    """
    from itertools   import groupby
    from operator    import itemgetter
    
    # load the data and make sure it is sorted by the first column
    sortby_key = itemgetter(0)
    data = sorted((map(int, line.split(',')) for line in open('data_shuffled.txt')),
                  key=sortby_key)
    
    # group by the first column
    grouped_data = []
    for key, group in groupby(data, key=sortby_key):
        assert key == len(grouped_data) # assume the first column is 0,1, ...
        grouped_data.append([trio[1:] for trio in group])
    
    # print the data
    for i, pairs in enumerate(grouped_data):
        print i, pairs
    

    Output:

    0 [[2, 7], [4, 7], [6, 7], [9, 5]]
    1 [[4, 7], [9, 0], [2, 5], [6, 8]]
    

提交回复
热议问题