Python unittest list comparison repr problem - python

Im writing some tests for more my python application for a company and now got stuck with the following problem:
I need to compare two list of lists and I always get a an error when converting the second automatically generated list: TypeError: repr returned non-string (type dict). Which means the list I'm trying to compare with self.assertListEqual(l1, l2) contains a sub list again, I already checked the structure and I'm always getting the same result: there is no sub list in the list, I have printed everything, evaluated the content multiply times and still getting the same error, now I'm a bit stuck and don't know if how to proceed further. This is the code I used to generate the list which is correct and should be structural the same as the list the function generates:
expected.append([])
expected[0].append(openers[0])
expected[0].extend(locks[0:5])
expected.append([])
expected[1].append(openers[1])
expected[1].extend(locks[6:10])
expected.append([other])
And this hard coded list is than compared to a dynamically created list which should be exactly the same
Thanks for any help, if more cod is required I will append it here

Related

Postgres/psycopg2 "executue_values": Which argument was not converted during string formatting?

I am using execute_values to insert a list of lists of values into a postgres database using psycopg2. Sometimes I get "not all arguments converted during string formatting", indicating that one of the values in one of the lists is not the expected data type (and also not NoneType). When it is a long list, it can be a pain to figure out which value in which list was causing the problem.
Is there a way to get postgres/psycopg2 to tell me the specific 'argument which could not be converted'?
If not, what is the most efficient way to look through the list of lists and find any incongruent data types per place in the list, excluding NoneTypes (which obviously are not equal to a value but also are not the cause of the error)?
Please note that I am not asking for help with the specific set of values I am executing it, but trying to find a general method to more quickly inspect the problem query so I can debug it.

How do you simplify .str.contains code with multiple contains variables?

I am using the Series.str.contains() function to find if a value in a dictionary is contained in a string from a specific column. My code works, but I am trying to simplify it.
I tried using a for loop to go through the values in a list. My attempt is down below.
total_joined_list=[joined_groc_lst,joined_util_lst]
for i in range(len(total_joined_list)):
groc_amount,util_amount=abs(round(df.loc[df['Description'].str.contains('\b'+i+'\b',na=False),'Amount'].sum(),2))
Here is the current working code.
joined_groc_lst = '|'.join(expenses_dict['Groceries'])
joined_util_lst = '|'.join(expenses_dict['Utilities'])
groc_amount=abs(round(df.loc[df['Description'].str.contains('\b'+joint_groc_lst+'\b',na=False),
'Amount'].sum(),2))
util_amount=abs(round(df.loc[df['Description'].str.contains('\b'+joint_util_lst+'\b',na=False),
'Amount'].sum(),2))
I expect my function to create two variables; groc_amount and util_amount, and I would be able to print my results. I got this error "TypeError: can only concatenate str (not "int") to str" and then added str() to the i in my for loop and get the following error "TypeError: cannot unpack non-iterable int object"
total_joined_list=[joined_groc_lst,joined_util_lst]
groc_amount, util_amount = (abs(round(df.loc[df['Description'].str.contains(f'\b{e}\b',na=False),'Amount'].sum(),2)) for e in total_joined_list)
I have change your forloop into a generator that allow unpacking data in order to get each items in the list.

Getting inaccurate response.corr in Psychopy

I use psychopy2 v1.85.2 for my experiment in Mac. I have gotten a message after an experiment as follows and then have some trouble in inaccurate response.corr though getting an accurate response.keys in excel. Please tell me how to get accurate response.corr.
FutureWarning:elementwise comparison failed;returning scalar
instead,but in the future will perform elementwise comparison
if (response0.keys == str(correctAns0) or (response0.keys == correctAns0):
response0.keys will return a list, even if it contains just a single value. This is why it is named .keys rather than .key. e.g. if the subject pushed the 'a' key, the results would be the single element list ['a'].
You should treat it as a list and make comparisons like yours to a specified single item within that list. e.g.
# test against the zeroth list item rather than the entire list:
if response0.keys[0] == str(correctAns0): # etc

Extracting the 'text' field from a JSON tweet element and adding it to string array python

I have a MongoDB collection full of tweets that I have collected and now I would like to perform sentiment analysis on them but I only want to perform this analysis on the 'text' field of each element. I had initially had a piece of code to determine whether or not the element had a text field so ive altered it to try to detect whether it has the text field and if so to add it to the next element of the array however I get a Type Error shown below.
appleSentimentText[record] = record.get('text')
TypeError: list indices must be integers, not dict.
I know this means that its to do with [record] not being an integer but im confused as to how I am to make it into an integer? Im new to Python so any help would be much appreciated. Here is my snippet of code below for reference.
appleSentimentText = []
for record in db.Apple.find():
if record.get('text'):
appleSentimentText[record] = record.get('text')
Lists require their indexes to be integer, hence the error.
If you want to add to the list, use list.append or list.insert methods.
appleSentimentText.append(record.get("text"))
List methods

What is a "Physically Stored Sequence" in Python?

I am currently reading Learning Python, 5th Edition - by Mark Lutz and have come across the phrase "Physically Stored Sequence".
From what I've learnt so far, a sequence is an object that contains items that can be indexed in sequential order from left to right e.g. Strings, Tuples and Lists.
So in regards to a "Physically Stored Sequence", would that be a Sequence that is referenced by a variable for use later on in a program? Or am not getting it?
Thank you in advance for your answers.
A Physically Stored Sequence is best explained by contrast. It is one type of "iterable" with the main example of the other type being a "generator."
A generator is an iterable, meaning you can iterate over it as in a "for" loop, but it does not actually store anything--it merely spits out values when requested. Examples of this would be a pseudo-random number generator, the whole itertools package, or any function you write yourself using yield. Those sorts of things can be the subject of a "for" loop but do not actually "contain" any data.
A physically stored sequence then is an iterable which does contain its data. Examples include most data structures in Python, like lists. It doesn't matter in the Python parlance if the items in the sequence have any particular reference count or anything like that (e.g. the None object exists only once in Python, so [None, None] does not exactly "store" it twice).
A key feature of physically stored sequences is that you can usually iterate over them multiple times, and sometimes get items other than the "first" one (the one any iterable gives you when you call next() on it).
All that said, this phrase is not very common--certainly not something you'd expect to see or use as a workaday Python programmer.

Categories

Resources