Check an Array for latest timestamp - python-2.7

[["a","some_variable_data","01.02.2021"]
["a","some_variable_data","01.03.2021"]
["a","some_variable_data","01.04.2021"]
["a","some_variable_data","11.02.2021"]
["b","some_variable_data","01.02.2020"]
["b","some_variable_data","01.03.2020"]
["b","some_variable_data","01.04.2020"]
["b","some_variable_data","11.02.2020"]]
i have to check the latest timestamp for each first array field and add this to the rows. so the result should look like:
[["a","some_variable_data","01.02.2021"]
["a","some_variable_data","01.03.2021"]
["a","some_variable_data","01.04.2021","latest"]
["a","some_variable_data","11.02.2021"]
["b","some_variable_data","01.02.2020"]
["b","some_variable_data","01.03.2020"]
["b","some_variable_data","01.04.2020","latest"]
["b","some_variable_data","11.02.2020"]]
i need some help/hint how to realize this. can anybody help me? i have to use python 2.7

I'm not sure if sorted([ that array ]) works, but you can try that.
Lets say: array = [ that bigger array you shared ].
We know the location of the dates: the 3rd element (index 2). It's also sorted on the first element of the list: "a" or "b"
A possible option is to split the array into two arrays: one starting with "a" and one with "b".
Next, you can sort on the array_a[2] element in the list. Depending on the date and month, you can see if it was before, or after.
At the end, you simply merge the big arrays together:
print([1,2,3]+[4,5,6]) # [1,2,3,4,5,6]

def latest(n):
n = list(filter(None, n)) #delete_empty
n.sort(key = lambda date: datetime.strptime(date, '%d.%m.%Y')) #sort date
n=n[::-1] #reverse list
#print(n)
latest=""
for lp in n:
latest=lp
break
return latest
found a way:
build list for each first key and sort them as datetime, then pick latest and rebuild the initial list

Related

find index based on first element in a nested list

I have a list that contains sublists. The sequence of the sublist is fixed, as are the number of elements.
schedule = [['date1', 'action1', beginvalue1, endvalue1],
['date2', 'action2', beginvalue2, endvalue2],
...
]
Say, I have a date and I want find what I have to do on that date, meaning I require to find the contents of the entire sublist, given only the date.
I did the following (which works): I created a intermediate list, with all the first values of the sublists. Based on the index i was able to retrieve its entire contents, as follows:
dt = 'date150' # To just have a value to make underlying code more clear
ls_intermediate = [item[0] for item in schedule]
index = ls_intermediate.index(dt)
print(schedule[index])
It works but it just does not seem the Python way to do this. How can I improve this piece of code?
To be complete: there are no double 'date' entries in the list. Every date is unique and appears only once.
Learning Python, and having quite a journey in front of me...
thank you!

How do I get the last element of a CMake list of unknown length?

I have a list of unknown length containing strings. I want to compare the last item with the second to last item, but I can't find an easy way to retrieve these elements so I can compare them.
I tried getting the length of the list and then using (length-1) as the index I pass into the list GET function, but this doesn't seem to work.
set(my_list a b c) # I don't actually know the length of the original list
list(LENGTH my_list list_len)
list(GET my_list (list_len-1) last_item) # doesn't work
I expect to have element c saved in the last_item variable, but it remains empty. What is the right way to do this in CMake?
You have to use math in order to perform mathematical operations.
list(LENGTH my_list list_len)
math(EXPR list_last "${list_len} - 1")
list(GET my_list ${list_last} last_item)
Edit: It is possible to get elements from the end of a list using negative numbers, you can use -1 to get the last item of a list:
list(GET my_list -1 last_item)

Scala. foreach in one element Lists of Dates

I want to create a function that works on a single date or over a period of time. For that I make a list of strings like this:
import com.github.nscala_time.time.Imports._
val fromDate = "2015-10-15".toLocalDate
val toDate = "2015-10-15".toLocalDate
val days = Iterator.iterate(fromDate)(_ + 1.day).takeWhile(_ <= toDate).map(_.toString)
Now I want to access days content:
scala> days.foreach(println)
2015-10-15
scala> days.foreach(day => println(day))
With the first foreach I get the only element in days list, but with the second I get nothing. This is just a sample, but I need to use the 2nd form, because I need to use day value inside the function.
If I use a range both methods work like they are supposed to...
Anyone knows why this behaviour?
Thanks in advance!
P.D. I don't want to use another method to create the list of strings (unless I can't find a solution for this)
Second function works in same way as first.
You've created Iterator object, which you can iterate only once.
To be able use it any amount of times just convert you iterator to list.
val daysL = days.toList

How to read each element within a tuple from a list

I want to write a program which will read in a list of tuples, and in the tuple it will contain two elements. The first element can be an Object, and the second element will be the quantity of that Object. Just like: Mylist([{Object1,Numbers},{Object2, Numbers}]).
Then I want to read in the Numbers and print the related Object Numbers times and then store them in a list.
So if Mylist([{lol, 3},{lmao, 2}]), then I should get [lol, lol, lol, lmao, lmao] as the final result.
My thought is to first unzip those tuples (imagine if there are more than 2) into two tuples which the first one contains the Objects while the second one contains the quantity numbers.
After that read the numbers in second tuples and then print the related Object in first tuple with the exact times. But I don't know how to do this. THanks for any help!
A list comprehension can do that:
lists:flatten([lists:duplicate(N,A) || {A, N} <- L]).
If you really want printing too, use recursion:
p([]) -> [];
p([{A,N}|T]) ->
FmtString = string:join(lists:duplicate(N,"~p"), " ")++"\n",
D = lists:duplicate(N,A),
io:format(FmtString, D),
D++p(T).
This code creates a format string for io:format/2 using lists:duplicate/2 to replicate the "~p" format specifier N times, joins them with a space with string:join/2, and adds a newline. It then uses lists:duplicate/2 again to get a list of N copies of A, prints those N items using the format string, and then combines the list with the result of a recursive call to create the function result.

How not to order a list of pk's in a query?

I have a list of pk's and I would like to get the result in the same order that my list is defined... But the order of the elements is begging changed. How any one help me?
print list_ids
[31189, 31191, 31327, 31406, 31352, 31395, 31309, 30071, 31434, 31435]
obj_opor=Opor.objects.in_bulk(list_ids).values()
for o in obj_oportunidades:
print o
31395 31435 31434 30071 31309 31406 31189 31191 31352 31327
This object should be used in template to show some results to the user... But how you can see, the order is different from the original list_ids
Would have been nice to have this feature in SQL - sorting by a known list of values.
Instead, what you could do is:
obj_oportunidades=Opor.objects.in_bulk(list_ids).values()
all_opor = []
for o in obj_oportunidades:
print o
all_opor.append(o)
for i in list_ids:
if i in all_opor:
print all_opor.index(i)
Downside is that you have to get all the result rows first and store them before getting them in the order you want. (all_opor could be a dictionary above, with the table records stored in the values and the PKeys as dict keys.)
Other way, create a temp table with (Sort_Order, Pkey) and add that to the query:
Sort_Order PKey
1 31189
2 31191
...
So when you sort on Sort_Order and Opor.objects, you'll get Pkeys it in the order you specify.
I found a solution in: http://davedash.com/2010/02/11/retrieving-elements-in-a-specific-order-in-django-and-mysql/ it's suited me perfectly.
ids = [a_list, of, ordered, ids]
addons = Addon.objects.filter(id__in=ids).extra(
select={'manual': 'FIELD(id,%s)' % ','.join(map(str,ids))},
order_by=['manual'])
This code do something similiar to MySQL "ORDER BY FIELD".
This guy: http://blog.mathieu-leplatre.info/django-create-a-queryset-from-a-list-preserving-order.html
Solved the problem for both MySQL and PostgreSQL!
If you are using PostgreSQL go to that page.