How do I nest a For Loop w/ IF statement to return a new list? - python-3.x

Can the return in an If statement append a list?
Is python aware that the list elements are actually dictionaries and that 'sublist' iterates over those elements?
I tried being data type specific after For previously and that doesn't help
Is the If statement actually accessing the dictionary?
My code:
In[1]: restaurants = [fork_fig, frontier_restaurant]
In [2]: def open_restaurants(restaurants):
for sublsit in restaurants:
op=[]
if sublist.get('is_closed')==False:
op.append(sublist.get('name'))
passed through their code:
In [1]: len(open_restaurants(restaurants))
Out[2]: NameErrorTraceback (most recent call last)
<ipython-input-14-e78afc732a29> in <module>
----> 1 len(open_restaurants(restaurants)) # 1
<ipython-input-13-56ad484d6dd9> in open_restaurants(restaurants)
2 for sublsit in restaurants:
3 op=[]
----> 4 if sublist.get('is_closed')==False:
5 op.append(sublist.get('name'))
6
NameError: name 'sublist' is not defined
and next: I think this is because the list i defined is not populating with the correct information.
In[3]: open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'
Out[4]:TypeErrorTraceback (most recent call last)
<ipython-input-15-bf5607d088f4> in <module>
----> 1 open_restaurants(restaurants)[0]['name'] # 'Fork & Fig'
TypeError: 'NoneType' object is not subscriptable

Your indentation may be not correct
You didn't return the result (probably return op) in your function

The problem here was that I was entering too much information.
The code that ended up working perfectly was as follows:
def open_restaurants(restaurants):
op=[]
for sublist in restaurants:
if sublist['is_closed']==False:
op.append(sublist)
return op
I separated op list from the for loop.
Previously, the NameError said sublist was not defined, yet it was
defined by including it in the For; to fix I removed .get() and
replaced it with list form x[].
Last, separated return from the .append() function.

Related

Getting TypeError: list indices must be integers when using list[:,colIndex] to get column data as list

I have a 2D list (a list of lists) and am trying to use the notation list[:,colIndex] to pull out a single column's data into another list, but I'm getting a TypeError: list indices must be integers error.
for example:
lst = [[1,2,3],[10,12,13]]
lst[:,0]
Returns:
Traceback (most recent call last):
File "<input>", line 2, in <module>
TypeError: list indices must be integers
I don't understand...
Edit:
Running this in Python 3.9 gives me:
TypeError: list indices must be integers or slices, not tuple
It would seem that the [:,colIndex] syntax isn't supported by lists and is available to numpy arrays only :(
However I can use: list(zip(*lst))[colIndex] instead from this answer https://stackoverflow.com/a/44360278/1733467

Python Statsmodels quasi-information criteria qic. Any example?

I must be doing something really wrong, for I just cannot write a code to get the quasi-information criteria from python statsmodels GEE method "qic". This method is listed the same way as the method "fit" (http://www.statsmodels.org/devel/generated/statsmodels.genmod.generalized_estimating_equations.GEE.html#statsmodels.genmod.generalized_estimating_equations.GEE) used in the code below:
model2 = sm.GEE.from_formula("BPXSY1 ~ RIDAGEYR + RIAGENDRx + BMXBMI + C(RIDRETH1)",groups="group",cov_struct=sm.cov_struct.Exchangeable(), data=da)
result2 = model2.fit()
But if I code "qic" the same way I coded "fit" the script does not run and the following message comes up:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-18-b3cc871449c1> in <module>()
----> 1 criteria = model2.qic()
AttributeError: 'GEE' object has no attribute 'qic'
I have also tried:
criteria = model2.qic(result2.params)
and:
criteria = result2.qic()
Nothing works. I get always the same Error message. It must be a syntax mistake. Can anyone help? Thanks

TypeError: 'list' object is not callable, this is irritating me

I have tried to map the title in the form of integer using list.
title_map = {'Mr':0, 'Miss':1, 'Mrs':2, 'Master':3, 'Dr':3, 'Rev':3, 'Major':3, 'Col':3, 'Mlle':3, 'Capt':3, 'Jonkheer':3, 'Lady':3,'Don':3, 'Mme':3, 'Ms':3, 'Countess':3,'Sir':3}
for dataset in train_test_data():
dataset['Title'] = dataset['Title'].map(title_map)
TypeError Traceback (most recent call last)
<ipython-input-63-e6e2af2d1334> in <module>()
1 title_map = {'Mr':0, 'Miss':1, 'Mrs':2, 'Master':3, 'Dr':3, 'Rev':3, 'Major':3, 'Col':3, 'Mlle':3, 'Capt':3, 'Jonkheer':3, 'Lady':3,'Don':3, 'Mme':3, 'Ms':3, 'Countess':3,'Sir':3}
2
----> 3 for dataset in train_test_data():
4 dataset['title'] = dataset['Title'].map(title_map)
TypeError: 'list' object is not callable
So for future reference you can use backticks to format code in stack overflow.
Anyway,you are getting that error because you are passing a list as the first argument to the map function. The map function takes a function and applies that function to some iterable object. If you include more details about what you are expecting to be in dataset['Title'] after the loop, I may be able to help you out more.
Docs for python map
Formatting in Stack Overflow

Extracting full name and country code of geolocation with Twitter

I am trying to extract full name and country code of a "place" from a json file that has thousands of tweets mined from Twitter API. I have tried to write the code several different times, but the code below makes the most sense to me. I was able to extract other data (hashtags, dates, followers with similar coding).
for i in range(len(data)):
if data[i]["place"] != "null":
get_place_info = data[i]["place"].get("full_name")
print(get_place_info)
else:
print("No place defined")
This is the error I get:
AttributeError Traceback (most recent call last)
in
3
4 if data[i]["place"] != "null":
----> 5 get_place_info = data[i]["place"].get("full_name")
6 print(get_place_info)
7
AttributeError: 'NoneType' object has no attribute 'get'
adding an answer from my previous comment...
have you tried changing your if statement to
if data[i]['place'] is not None:

Variable type is list but python says object type float does not have an attribute len

I am using Python 3 and the code is as follows
# Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0.
left_space=capacity
vpw=[]
for i in range (0,len(weights)-1):
print (i)
vpw.append(values[i]/weights[i])
vpw_s=[]
v_s=[]
w_s=[]
k=0
vpw=list(vpw)
print (type(vpw))
while (len(vpw) > 0):
j = vpw.index(max(vpw))
vpw_s.append(vpw[j])
v_s.append(values[j])
w_s.append(weights[j])
vpw=vpw.pop(j)
k=k+1
for i in range (0, len(w_s)-1):
if (left_space> 0):
w_u=min(w_s[i],left_space)
value=value+w_u*vpw_s[i]
# write your code here
return value
if __name__ == "__main__":
opt_value = get_optimal_value(10, [3,4,1], [10,12,80])
print("{:.10f}".format(opt_value))
This gives an error -
<class 'list'>
Traceback (most recent call last):
File "/home/main.py", line 35, in <module>
opt_value = get_optimal_value(10, [3,4,1], [10,12,80])
File "/home/main.py", line 16, in get_optimal_value
while (len(vpw) > 0):
TypeError: object of type 'float' has no len()
Is the variable vpw not of the type list ?
The problem is not when you first execute the while, but the second time. You have inside the loop:
vpw=vpw.pop(j)
But, the return value from pop() is actually the element that you popped, and the list is modified in place, so you change vpw from a list to a float, thus the second time you execute the while you are trying to do len() on a float. The simple fix is just to delete the assignment:
vpw.pop(j)
The problem is not when you do the first iteration but rather the second and onwards, where you say vpw=vpw.pop(j), pop returns the value from that index, and deltes from the list, therefore vpw is now a float. You can try this by putting the print type inside the while loop. I recommend reading this, this, to see what you are trying to go for, I believe you need vpw.remove(max(vpw).

Resources