adding a list to the function by index - python

I have a function which takes the list as an input. The list is as follows :
[ [ [179.0,77.0], [186.0,93.0], [165.0,91.0 ],..],
[ [178.0,76.0 ],[185.0,93.0 ],[164.0,91.0 ] ,..],...]
I want to give this list by index so that the function will normalize(already written) the data for each index and predict(already written the function logic) for each index. The example is as follows :
normalzed_list = normalize(list)
predict(normalized_list) # this function should predict based on the index of the list.
I would appreciate any help. Thank you.

I would use map()
normalized = map(normalize, lst)
predicted = map(predict, normalized)
result = list(predicted) # evaluate the generator
For debugging purposes you would want to put list() around the first map().
Edit:
The index you can get by enumerate().
predicted = map(lambda e: predict(e[0], e[1]), enumerate(normalized))
e[0] has the index, e[1] the normalized list.

If you already know the index of the list element, can simply do this
normalized_list = normalize(list[idx]). Where idx is the known index.

Related

How to feed a function one value at a time from a list of lists?

I have a function modify as follows:
list_with_chunks = [['hi','hello','how are you?'],['i','am','fine'],['what','about you?','.']]
flatten_list = ['hi','hello',...]
empty_list = []
# building the function to convert our sentences in list_with_chunks into another form:
def modify(sentence):
# do stuff here
# returning the result and appending them in empty_list
return empty_list.append(sentence*2)
I call the function as below:
for i in flatten_list:
modify(i)
But, I want to send each sentence directly from list_with_chunks instead of flattening it and append the result in empty_list. How do I do that?
TIA.
I don't understand the question entirely! But is this what you looking for:
for x in list_with_chunks:
for y in x:
modify(y)
You just need to iterate every element inside list again in order to add them in the empty list.
Use a nested loop through list_with_chunks.
for i in range(len(list_with_chunks)):
for j in range(len(list_with_chunks[i])):
modify(list_with_chunks[i][j], top_n=5)

Is there a way to write a module that contains a function that returns a list of lists?

Example, given this short dataset:
data = [ ['6623', '2009-11-15'],
['6623', '2010-04-04'],
['6623', '2011-03-06'],
['6623', '2011-03-19'],
['6623', '2011-09-07'],
['6624', '2011-09-11'],
['6624', '2012-01-04'],
['6624', '2012-04-25'],
['6624', '2012-08-03'],
['6625', '2012-07-15'],
['6622', '2010-10-05'] ]
I need to write down a python code to get a list of lists with max and min value of the first column + its associated day. Following the previous dataset:
[ ['6622', '2010-10-05'],
['6625', '2012-07-15'] ]
I started with this code, then I stopped my self because I do not have any idea how to combine min/max value with its associated day
def getDateRange['a', 'b', 'c']:
minval = min[data]
maxval= max[data]
In Python defining and calling a function both use parentheses rather than square brackets to enclose parameters. Since sequences are ordered according to the order of the first item, or the second item, if the first items are the same, etc., you can simply call max and min with the list of lists to obtain the desired output:
def getDateRange(data):
return [min(data), max(data)]
so that given your sample input, getDateRange(data) returns:
[['6622', '2010-10-05'], ['6625', '2012-07-15']]

IndexError: list assignment index out of range - python

I have a problem with my code, I just want to write the result in csv and i got IndexError
seleksi = []
p = FeatureSelection(fiturs, docs)
seleksi[0] = p.select()
with open('test.csv','wb') as selection:
selections = csv.writer(selection)
for x in seleksi:
selections.writerow(selections)
In p.select is:
['A',1]
['B',2]
['C',3]
etc
and i got error in:
seleksi[0] = p.select()
IndexError: list assignment index out of range
Process finished with exit code 1
what should i do?
[], calls __get(index) in background. when you say seleksi[0], you are trying to get value at index 0 of seleksi, which is an empty list.
You should just do:
seleksi = p.select()
When you initlialize a list using
seleksi = []
It is an empty list. The lenght of list is 0.
Hence
seleksi[0]
gives an error.
You need to append to the list for it to get values, something like
seleksi.append(p.select())
If you still want to assign it based on index, initialize it as array of zeros or some dummy value
seleksi = [0]* n
See this: List of zeros in python
You are accesing before assignment on seleksi[0] = p.select(), this should solve it:
seleksi.append(p.select())
Since you are iterating over saleksi I guess that what you really want is to store p.select(), you may want to do seleksi = p.select() instead then.
EDIT:
i got this selections.writerow(selections) _csv.Error: sequence
expected
you want to write x, so selections.writerow(x) is the way to go.
Your final code would look like this:
p = FeatureSelection(fiturs, docs)
seleksi = p.select()
with open('test.csv','wb') as selection:
selections = csv.writer(selection)
for x in seleksi:
selections.writerow(x)

Working with lists - Python

i ran into a little logic problem and trying to figure it out.
my case is as follows:
i have a list of items each item represents a Group
i need to create a set of nested groups,
so, for example:
myGroups = ["head", "neck", "arms", "legs"]
i need to get them to be represented like this:
(if you can imaging a folder structure)
head
|_> neck
|_> arms
|_>legs
and so on until i hit the last element.
what i thought would work (but don't know really how to advance here) is:
def createVNTgroups(self, groupsData):
for i in range(len(groupsData)):
print groupsData[i]
for q in range(1, len(groupsData)):
print groupsData[q]
but in this case, i am running over same elements in 'i' that i already took with 'q'.
could someone give me a hint?
thanks in advance!
If I understood well, you want a nested structure. For this case, you can use a recursive function:
myGroups = ["head", "neck", "arms", "legs"]
def createVNTgroups(alist):
temp = alist[:] # needed because lists are mutable
first = [temp.pop(0)] # extract first element from list
if temp: # if the list still contains more items,
second = [createVNTgroups(temp)] # do it recursively
return first + second # returning the second object attached to the first.
else: # Otherwise,
return first # return the last element
print createVNTgroups(myGroups)
this produces a nested list:
['head', ['neck', ['arms', ['legs']]]]
Is that what you were looking for?
>>> m
['head', 'neck', 'arms', 'legs']
>>> reduce(lambda x,y:[x,y][::-1] if x!=y else [x], m[::-1],m[-1])
['head', ['neck', ['arms', ['legs']]]]

How do I pull certain values from a list of lists in python?

def get_monthly_averages(original_list):
#print(original_list)
daily_averages_list = [ ]
for i in range (0, len(original_list)):
month_list = i[0][0:7]
volume_str = i[5]
#print(volume_str)
adj_close_str = i[6]
#print(adj_close_str)
daily_averages_tuple = (month_list,volume_str,adj_close_str)
daily_averages_list.append(daily_averages_tuple.split(','))
return daily_averages_list
I have a list like
[
['2004-08-30', '105.28', '105.49', '102.01', '102.01', '2601000', '102.01'],
['2004-08-27', '108.10', '108.62', '105.69', '106.15', '3109000', '106.15'],
['2004-08-26', '104.95', '107.95', '104.66', '107.91', '3551000', '107.91'],
['2004-08-25', '104.96', '108.00', '103.88', '106.00', '4598900', '106.00'],
['2004-08-24', '111.24', '111.60', '103.57', '104.87', '7631300', '104.87'],
['2004-08-23', '110.75', '113.48', '109.05', '109.40', '9137200', '109.40'],
['2004-08-20', '101.01', '109.08', '100.50', '108.31', '11428600', '108.31'],
['2004-08-19', '100.00', '104.06', '95.96', '100.34', '22351900', '100.34']
]
I am attempting to pull certain multiple values from within each list within the 'long' list. I need to use beginning python techniques. For instance, we haven't learned lambda in the class as of yet. MUST use beginning techniques.
as of right now the lines using i[][] are giving me a type error saying that 'int' is not subscriptable.
Your variable i is an integer. You should be indexing into original_list and not i.
I think you wwant
month_list = original_list[i][0][0:7]
volume_str = original_list[i][5]
#print(volume_str)
adj_close_str = original_list[i][6]
Don't use range to iterate over lists. Do this:
for datestr, n1, n2, n3, someval, otherval in original_list:
#do your stuff here
This will iterate over every list in original_list, and assign the 6 elements of each such list to the variables given.

Categories

Resources