Python разбил список на различные списки по месяцам - PullRequest
0 голосов
/ 30 мая 2018

У меня есть список объектов (модель Джанго), которые содержат атрибут даты среди других.день / месяц / год, и мне нужно разделить его на группы по месяцам и годам, поэтому, если у меня есть:

list_dates = ['1-10-2018','4-10-2018','1-11-2018',
            '6-10-2018', '3-10-2018', '6-11-2018', '9-11-2018']

, что на самом деле:

list_objects = [a,b,c,d,e,f,g...z]

edit: и каждый объект(модель) имеет date = models.Datetime(), и мне нужно выбрать и сгруппировать объекты, имеющие одинаковые месяц и год.

превратить его в

splitted_list = {[a,b,e],[c,d,e]}# same month, same year grouped together

list_grouped = {['1-10-2018','4-10-2018','1-10-2018','6-10-2018'],

['3-11-2018', '6-11-2018', '9-11-2018']}

, и я не смог найтипростой или выполнимый способ сделать это Надеюсь, что кто-то имеет представление о том, как это сделать.Уже несколько дней пытаюсь.

'class my_model<(models.Model):
    owner = models.ForeignKey('User', on_delete=models.CASCADE, related_name="model_prods")
    ...  
    ...

class list_v2(models.Model):
    list_owner= models.ForeignKey(my_model, related_name='date_list', on_delete=models.CASCADE)
    date = models.DateField()
    ...
    ...

Ответы [ 3 ]

0 голосов
/ 30 мая 2018

@ Zealot91 , вы можете попробовать приведенные ниже примеры кода.

Примечание: Вы не можете использовать такие выражения, как {[1, 2, 3], [2, 3, 4], [2, 3, 4]} в Python, но{(1, 2, 3), (2, 3, 4), (2, 3, 4)} в порядке.

Поэтому я предлагаю вам использовать / создать [[1, 2, 3], [2, 3, 4], [2, 3, 4]] список типов в качестве конечного результата, или вы можете использовать dictionay, например {'2018': {'10':['12-10-2018', '12-10-2018'], '11': ['12-11-2018', '9-11-2018']}}, для организации ваших дат на основе года и месяца.

>>> s = {[1, 2, 3], [2, 3, 4], [2, 3, 4]}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>
>>> s = {(1, 2, 3), (2, 3, 4), (2, 3, 4)}
>>> s
set([(2, 3, 4), (1, 2, 3)])
>>>

«Пример 1

import json

# List of dates
list_dates = [
                '1-10-2018','4-10-2018','1-11-2018',
                '6-10-2018', '3-10-2018', '6-11-2018', 
                '9-11-2018'
            ]

d = {}

for date in list_dates:
    day, month, year = date.split('-')

    if year in d:
        if month in d[year]:
            d[year][month].append(date)
        else:
            d[year][month] = [date]
    else:
        d[year] = {month: [date]}

# Pretty printing d (Example 1.1: dictionary)
print(json.dumps(d, indent=4))
"""
    {
        "2018": {
            "11": [
                "1-11-2018",
                "6-11-2018",
                "9-11-2018"
            ],
            "10": [
                "1-10-2018",
                "4-10-2018",
                "6-10-2018",
                "3-10-2018"
            ]
        }
    }
"""

# Creating and pretty printing list_grouped (Example 1.2: list of lists)
list_grouped = [months_list for year in d.values() for months_list in year.values()]
print(json.dumps(list_grouped, indent=4))
"""
    [
        [
            "1-11-2018",
            "6-11-2018",
            "9-11-2018"
        ],
        [
            "1-10-2018",
            "4-10-2018",
            "6-10-2018",
            "3-10-2018"
        ]
    ]
"""

» Пример 2

# List of dates
import json

list_dates = [
                '1-10-2018','28-01-2017', '4-10-2018','1-11-2018',
                '6-10-2018', '3-10-2018', '6-12-2016', '6-11-2018', 
                '9-11-2018', '15-11-2016', '14-05-1992', '03-11-2017',
                '1-10-2018','25-01-2017', '4-11-2017','1-11-2016',
                '6-10-2018', '3-11-2016', '6-12-2017', '6-10-2013', 
                '9-12-2014', '15-10-2013', '20-05-1992', '03-12-2017',
                '19-12-2014', '15-10-2013', '20-05-1992', '03-12-2017'
            ]

d = {}

for date in list_dates:
    day, month, year = date.split('-')

    if year in d:
        if month in d[year]:
            d[year][month].append(date)
        else:
            d[year][month] = [date]
    else:
        d[year] = {month: [date]}

# Pretty printing d (Example 2.1: dictionary)
print(json.dumps(d, indent=4))

"""
    {
        "1992": {
            "05": [
                "14-05-1992",
                "20-05-1992",
                "20-05-1992"
            ]
        },
        "2018": {
            "11": [
                "1-11-2018",
                "6-11-2018",
                "9-11-2018"
            ],
            "10": [
                "1-10-2018",
                "4-10-2018",
                "6-10-2018",
                "3-10-2018",
                "1-10-2018",
                "6-10-2018"
            ]
        },
        "2014": {
            "12": [
                "9-12-2014",
                "19-12-2014"
            ]
        },
        "2017": {
            "11": [
                "03-11-2017",
                "4-11-2017"
            ],
            "12": [
                "6-12-2017",
                "03-12-2017",
                "03-12-2017"
            ],
            "01": [
                "28-01-2017",
                "25-01-2017"
            ]
        },
        "2016": {
            "11": [
                "15-11-2016",
                "1-11-2016",
                "3-11-2016"
            ],
            "12": [
                "6-12-2016"
            ]
        },
        "2013": {
            "10": [
                "6-10-2013",
                "15-10-2013",
                "15-10-2013"
            ]
        }
    }
"""

# Creating and pretty printing list_grouped (Example 2.2: list of lists)
list_grouped = [months_list for year in d.values() for months_list in year.values()]
print(json.dumps(list_grouped, indent=4))

"""
    [
        [
            "14-05-1992",
            "20-05-1992",
            "20-05-1992"
        ],
        [
            "1-11-2018",
            "6-11-2018",
            "9-11-2018"
        ],
        [
            "1-10-2018",
            "4-10-2018",
            "6-10-2018",
            "3-10-2018",
            "1-10-2018",
            "6-10-2018"
        ],
        [
            "9-12-2014",
            "19-12-2014"
        ],
        [
            "03-11-2017",
            "4-11-2017"
        ],
        [
            "6-12-2017",
            "03-12-2017",
            "03-12-2017"
        ],
        [
            "28-01-2017",
            "25-01-2017"
        ],
        [
            "15-11-2016",
            "1-11-2016",
            "3-11-2016"
        ],
        [
            "6-12-2016"
        ],
        [
            "6-10-2013",
            "15-10-2013",
            "15-10-2013"
        ]
    ]
"""
0 голосов
/ 30 мая 2018

На самом деле вы можете группировать по месяцам и годам, непосредственно пометив набор запросов, например:

filtered_queryset = queryset.annotate(month=TruncMonth('date'), year=TruncYear('date'))
filtered_queryset.values_list('month', 'year')

https://docs.djangoproject.com/en/2.0/ref/models/database-functions/#datefield-truncation

0 голосов
/ 30 мая 2018

Вы можете использовать объект dict для отслеживания комбинации месяца и года в качестве ключей и их соответствующей позиции в списке результатов в качестве значений этих ключей.

Пример :

list_objects = [a, b, c...]
month_year_dict = {}
result = []

for obj in list_objects:
    dt = obj.date_field_name
    day, month, year = dt.day, dt.month, dt.year

    key = month + "-" + year
    if month_year_dict.get(key, None):
        result[month_year_dict[key]].append(obj)
    else:
        result.append([obj])
        month_year_dict[key] = len(result) - 1

print(result)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...