The familiar pythonic slicing conventions of myList[-1:][0] and myList[-1] are not available for Mongoengine listFields because it does not support negative indices. Is there an elegant way to get the last element of a list?
Error verbiage for posterity:
IndexError: Cursor instances do not support negative indices
You can access the last item with this code:
myList[len(myList) - 1]
Do not use len on a QuerySet, because this will evaluate the query set. Django docs:
A QuerySet is evaluated when you call len() on it. This, as you might
expect, returns the length of the result list.
If you just want to get the length of the set use count instead. So answering your question, I would use something like myList[myList.count() - 1].
Related
I have a simple problem. I'm new to python and programming so I think i miss something.
The variable "account_info" is assigned earlier and is a list of lists with 4 elements each. The variable current is a user input value, which (should) appear as the first element of the lists in the list account_info.
I want to iterate over the lists in the list and compare if the first element is equal to "current".
This is the code:
for i in account_info:
if current == account_info[i][0]:
email = account_info[i][1]
additional = account_info[i][2]
pw = account_info[i][3]
print(email)
I get an error in pycharm, when running that code. It seems that I can't iterate over the lists like that, can please someone explain and show a different solution?
Thank you
As #ForceBru commented, your issue is due to how for loops in Python work. The value you get from the loop is not an index into the iterable object you're looping on, rather, it's a value from the iterable. That makes your indexing with it later almost certainly wrong (though in certain contexts it might make sense, if you have a list that contains indexes into itself).
In your case, you probably want to do something more like this:
for account in accounts_info:
if current == account[0]: # note, only the inner indexing is needed
email = account[1]
additional = account[2]
pw = account[3]
Since you're expecting the inner lists to contain four values, you could even unpack the account values that you get from iterating directly into the inner variables. Though this would happen unconditionally, so it might not do what you want. Here's what that would look like, with the print call you were doing after the loop instead moved inside the conditional (so you only print the one email address that corresponds to the value in current):
for account_id, email, additional, pw in account_info: # unpack unconditionally
if account_id == current: # use the convenient name here
print(email) # print only in the conditional
In the rare case where you really do need to iterate over indexes, you can use the range type, which behaves like a sequence of integers (starting at zero by default). So you could replace your loop with this version and the body would work as you had intended (though this is less idiomatic Python than the previous versions).
for i in range(len(accounts_info)):
If you need both the index and the current value, you can use the enumerate function, which yields 2-tuples of index and value as you iterate over it. This is often handy when you need to reassign values in a list some times:
for i, account in enumerate(accounts_info):
if account[0] == current:
accounts_info[i] = new_value # replace the whole account entry
I am trying to add the current dictionary to a Redis list using a dictionary comprehension and then to print out the first (aka current) keys and values of that list. I say current because this is a process I will be continuing with a while loop to have the list building over time, but I have to always access the first keys/values.
I am sure I am totally butchering this, but this is what I have:
adict = {"a":1,"b":2,"c":3}
{rserver.rpush("list",value) for value in adict}
print(float(rserver.lindex("list",0)))
I need to get a list of both keys and values back.
Help would be MUCH appreciated. Thanks!
I am not quite positive on what your redis-list should contain (please include your expected result in the question), but assuming it should at the end of inserts look something like this ["a:1", "b:1", "c:1"], you can achieve this with
adict = {"a":1,"b":2,"c":3}
for key,value in adict.items():
rserver.rpush("list", ":".join([key, value]))
print(float(rserver.lindex("list",0))) #>>> "a:1"
(as you have not included what interface rserver exactly is, it is a bit hard to guess on its exact behavior)
I am new in python scripting and I trying to figure out w basics about a program source code.
I am struggling to understand these two expressions:
First :
index = [0]*3, It creates an index but how?
Second :
random.random_shuffle(mylist[-1]), what does "-1" mean? The last item in the list?
Many thanks in advance
Well, you are right in one case. Although nothing in your code uses a dictionary. But, maybe these examples will help clear things up.
my_zeroes = [0]*3
assert my_zeroes == [0, 0, 0]
assert [0, 1, 2, 3][-1] == 3
In the first line the syntax you have here will create a list containing three zeroes. Your statement First : index = [0]*3, It creates an index doesn't really make sense. Indexes are inherent to certain data structures like lists and tuples, for example, you don't 'create' them as such. But hopefully my example makes it a bit clearer what is happening here.
In the second line we just check the above fact is true. If it wasn't true it would throw an AssertionError, so assert is a useful debugging tool.
In the third line we assert the answer to your second question: [some_list][-1] does indeed perform a negative index into the last item of the list. Unless the list in question is empty in which case [][-1] will give you an IndexError, as will any other index for that matter while trying to index into the empty list.
You can check out the Python tutorial to get more familiar with the syntax. Good luck!
I have an Array List in groovy in below format. I want the sum of integer values in this list.
[ {"value":1}, {"value":1}, {"value":10}, {"value":11}, {"value":12}]
Expected Output
1+1+10+11+12=35
Oh it's very easy.
list.value.sum()
I would prefer using the Groovy Spread Operator.
The Spread Operator (*.) is used to invoke an action on all items of an aggregate object.
Specific to your question, the best way coding the desired result is:
list*.value.sum()
The difference is only a * but it is best practice to use the language correctly.
Here are two examples:
sum(list(map(lambda x:x,range(10))))
and
sum(range(10))
The second example does not require a list(), but the first one does. Why?
How do I know when is list() a necessity? Similarly using list() for min() and max().
I am running python 3.3.5 with ipython 2.2.0. Here is what I see:
print(sum) results in <built-in function sum> from python console and <function sum at 0x7f965257eb00> from ipythonNotebook. Looks like an issue with hidden imports in notebook.
Neither of the examples require the use of list. The sum builtin function works with any iterable, so converting the result of map to a list isn't necessary.
Just in case, make sure you are indeed using the builtin sum function. Doing something like from numpy import * would override that. (you can simply print sum and see what you get).
I guess the 1st one just enforces and expects the output of the map function to be a list because if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables.
But either way base on your example, it would still work.