根据月份python分割日期

时间:2018-06-25 15:15:35

标签: python datetime

我有如下日期列表

[self.manager GET:@"http://www.samplewebsite.net/api" parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {

        aryNearMeList = responseObject;

        for (int i = 0; i < aryNearMeList.count; i++) {
        CLLocation *merchantLocation = [[CLLocation alloc] initWithLatitude:[[_serverDataArr [i]valueForKey:@"latitude"] doubleValue] longitude:[[_serverDataArr [i]valueForKey:@"longitude"] doubleValue]];
        CLLocationDistance meters = [merchantLocation distanceFromLocation:location];

        NSString *abc = [NSString stringWithFormat:@"~ %.2f km", meters / 1000.0];
        NSLog(@"243 %@",abc);  //WILL RETURN DISTANCE HERE. HOW CAN I SORT BY DISTANCE ASC??
         }

        NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"abc" ascending:YES
    comparator:^NSComparisonResult(id obj1, id obj2) {
        float value1 = [obj1 floatValue];
        float value2 = [obj2 floatValue];
        if (value1 == value2) {
            return NSOrderedSame;
        } else if (value1 > value2) { 
            return NSOrderedDescending;
        } else {
            return NSOrderedAscending;
        }
    }];
        _serverDataArr = [aryNearMeList sortedArrayUsingDescriptors:@[sortDescriptor]];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });

    } failure:^(NSURLSessionTask *operation, NSError *error) { }

我希望上述数组按如下方式拆分

[['2018-05-24', 6000], ['2018-05-25', 43300], ['2018-06-27', 0], ['2018-06-28', 20400], ['2018-06-03', 600], ['2018-07-03', 1100]]

在Python中有什么方法可以做到吗?

2 个答案:

答案 0 :(得分:1)

您可以使用itertools.groupby做类似的事情

>>> import itertools 
>>> 
>>> l=[['2018-05-24', 6000], ['2018-05-25', 43300], ['2018-06-27', 0], ['2018-06-28', 20400], ['2018-06-03', 600], ['2018-07-03', 1100]]
>>> [list(v) for k,v in groupby(l, lambda e: e[0])]
[[['2018-05-24', 6000]], [['2018-05-25', 43300]], [['2018-06-27', 0]], [['2018-06-28', 20400]], [['2018-06-03', 600]], [['2018-07-03', 1100]]]
>>> 

答案 1 :(得分:0)

使用var exampleData = Device( data: DeviceData( deviceID: "someID", type: "messages", attributes: Attributes( name: "Hello World", asdf: "This is my message", payload: Payload( example: "World" ) ) ), meta: Meta( currentPage: 123, nextPage: 456, deviceID: ["asfd-asdf-asdf-asdf-asdfcasdf"] ) ) 中的groupby

例如:

itertools

输出:

from itertools import groupby
import pprint
res = []
l = [['2018-05-24', 6000], ['2018-05-25', 43300], ['2018-06-27', 0], ['2018-06-28', 20400], ['2018-06-03', 600], ['2018-07-03', 1100]]
for k, g in groupby(l, lambda x: x[0][:7]):
    res.append(list(g))

pprint.pprint(res)