1👍
Updated after clarification:
The problem as I understand it:
- You have a dataset that is split into several lists, one list per field.
- Every list has the records in the same order. That is,
user[x]
‘s rating value is necessarilyrating_values[x]
.
You need to merge that information into a single list of composite items. You’d use zip()
for that:
merged = zip(user, next_level, comment_values, likes_values, rating_values, date)
# merged is now [(user[0], next_level[0], comment_values[0], ...),
# (user[1], next_level[1], comment_values[1], ...),
# ...]
From there, you can simply sort your list using sorted()
:
result = sorted(merged, key=lambda i: (i[5], i[0]))
The key
argument must be a function. It is given each item in the list once, and must return the key that will be used to compare items. Here, we build a short function on the fly, that returns the date and username, effectively telling things will be sorted, first by date and if dates are equal, then by username.
[Past answer about itertools.chain
, before the clarification]
ab = list(itertools.chain(
(i['name'] for i in user),
(i['rating'] for i in next_level),
(i['count'] for i in comment_values),
(i['count'] for i in likes_values),
(i['value'] for i in rating_values),
(i['date'] for i in date),
))
The point of using itertools.chain
is usually to avoid needless copies and intermediary objects. To do that, you want to pass it iterators.
chain
will return an iterator that will iterate through each of the given iterators, one at a time, moving to the next iterator when current stops.
Note every iterator has to be wrapped in parentheses, else python will complain. Do not make it square brackets, at it would cause an intermediary list to be built.
- Excluding objects from Django queryset based on recency
- Django- how to serve an image in all templates of django app?
0👍
date, rating_values,likes_values,comment_values,next_level,user = (list(t) for t in zip(*sorted(zip(date, rating_values,likes_values,comment_values,next_level,user))))