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)
Related
I am a student relatively new to coding, using Python at GCSE level and I am struggling to see where I am going wrong with this piece of code, used to correct different students marks by an adjustment factor. Why am I getting an error when both lists have the same number of items in them?
wrongMark = [72,75,23,54,48]
adFactor = [1.25,1.1,1.8,1.3,0.9]
newMark = []
examTable = [["Doc","Sarah","Jar-Jar","Jake","Ben"],
wrongMark,
adFactor
]
#print(examTable)
for item in wrongMark:
results = item*adFactor[item]
newMark.append(results)
print(newMark)
Inside your for loop put in a line to print(item)
You’ll see it is the value in wrongMark, not the index.
You probably want
For index in range(len(wrongMark)):
The error is that you are using for item in wrongMark. In the first iteration, the loop will assign item with value 75 and the list adFactor doesn't have 75 items ;)
One way to solve this is just changing the loop to:
for item in range(len(wrongMark)):
results = wrongMark[item]*adFactor[item]
newMark.append(results)
The problem is at this row:
results = item*adFactor[item]
For the first iteration of the for loop, you are trying to access the 72th cell in the list adFactor.
That is why you get "list index out of range"
The error is In the code: results = item*adFactor[item]
It is easier to note the error when you imagine the first iteration of your loop to be : result = 72 * adFactor[72]
You get an out of index error because the list adFactor doesnt have a 72nd term.
you need to use index while iterating. You are using value which is 72 for first iteration. That is why it out of range error. Use something like : for idx in range(len(wrongMark)):
results = wrongMark[idx]*adFactor[idx]
newMark.append(results)
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.
import imgcompare
...
for filename in os.listdir(myPath):
if filename.endswith(".png"):
listIm1.append(filename)
for filename2 in os.listdir(myPath2):
if filename2.endswith(".png"):
listIm2.append(filename2)
so i fill my two lists with images,now I would like to compare the images of the two lists one by one following the same index, for example:listIm1[0] with listImg2[0]listIm1[1] with listImg2[1]and so on... and that's the code:
for item in listIm1:
ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
print ifSame
but get the error:
same = imgcompare.is_equal(listIm1[item], listIm2[item], tolerance=2)
TypeError: list indices must be integers, not str
it seems that imgcompare.is_equal() does not work with lists, is there some pythonic expedient to make it
works?
since
if filename2.endswith(".png"):
listIm2.append(filename2)
for item in listIm1:
# item = "someimagine.png"
ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
#listIm1[someimagine.png] is what you are asking => retrun Type Error
I guess you are looking for something like this:
edit:
import os
for filename in os.listdir(myPath):
if filename2.endswith(".png"):
img_path = os.path.join(myPath,filename2)
listIm2.append(img_path)
listIm1 = []
listIm2 = []
for i in range(len(listIm1)):
ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)
print ifSame
and it's better if len(listIm1) == len(listIm2)
The problem here is that you are trying to get the index of listIm1 by using item. What you want to do is use a range(), like:
for i in range(len(listIm1)):
ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)
As #Matt pointed out, this will only work if you know the lists are the same length beforehand, otherwise it will throw an index error.
You are using a for each loop, which grabs each element in your provided list listIm1 and stores it in a temp variable item, you then pass item (which is a string) as an index both of your lists. Indices of a list must be an integer, and that is the error you are getting.
for dir1_file in listIm1:
for dir2_file in listIm2:
ifSame = imgcompare.is_equal(dir1_file,dir2_file,tolerance=2)
print ifSame
This code uses two for each loops, it looks at each element in both of the lists and uses them as the arguments for your method.
I'm trying to manipulate a list of items in python but im getting the error "AttributeError: 'list' object has no attribute 'split'"
I understand that list does not understand .split but i don't know what else to do. Below is a copy paste of the relevant part of my code.
tourl = 'http://data.bitcoinity.org/chart_data'
tovalues = {'timespan':'24h','resolution':'hour','currency':'USD','exchange':'all','mining_pool':'all','compare':'no','data_type':'price_volume','chart_type':'line_bar','smoothing':'linear','chart_types':'ccacdfcdaa'}
todata = urllib.urlencode(tovalues)
toreq = urllib2.Request(tourl, todata)
tores = urllib2.urlopen(toreq)
tores2 = tores.read()
tos = json.loads(tores2)
tola = tos["data"]
for item in tola:
ting = item.get("values")
ting.split(',')[2] <-----ERROR
print(ting)
To understand what i'm trying to do you will also need to see the json data. Ting outputs this:
[
[1379955600000L, 123.107310846774], [1379959200000L, 124.092526428571],
[1379962800000L, 125.539504822835], [1379966400000L, 126.27024617931],
[1379970000000L, 126.723474983766], [1379973600000L, 126.242406356837],
[1379977200000L, 124.788410570987], [1379980800000L, 126.810084904632],
[1379984400000L, 128.270580796748], [1379988000000L, 127.892411269036],
[1379991600000L, 126.140579640523], [1379995200000L, 126.513705084746],
[1379998800000L, 128.695124951923], [1380002400000L, 128.709738051044],
[1380006000000L, 125.987767097378], [1380009600000L, 124.323433535528],
[1380013200000L, 123.359378559603], [1380016800000L, 125.963250678733],
[1380020400000L, 125.074618194444], [1380024000000L, 124.656345088853],
[1380027600000L, 122.411303435449], [1380031200000L, 124.145747100372],
[1380034800000L, 124.359452274881], [1380038400000L, 122.815357211394],
[1380042000000L, 123.057706915888]
]
[
[1379955600000L, 536.4739135], [1379959200000L, 1235.42506637],
[1379962800000L, 763.16329656], [1379966400000L, 804.04579319],
[1379970000000L, 634.84689741], [1379973600000L, 753.52716718],
[1379977200000L, 506.90632968], [1379980800000L, 494.473732950001],
[1379984400000L, 437.02095093], [1379988000000L, 176.25405034],
[1379991600000L, 319.80432715], [1379995200000L, 206.87212398],
[1379998800000L, 638.47226435], [1380002400000L, 438.18036666],
[1380006000000L, 512.68490443], [1380009600000L, 904.603705539997],
[1380013200000L, 491.408088450001], [1380016800000L, 670.275397960001],
[1380020400000L, 767.166941339999], [1380024000000L, 899.976089609997],
[1380027600000L, 1243.64963909], [1380031200000L, 1508.82429811],
[1380034800000L, 1190.18854705], [1380038400000L, 546.504592349999],
[1380042000000L, 206.84883264]
]
And ting[0] outputs this:
[1379955600000L, 123.187067936508]
[1379955600000L, 536.794013499999]
What i'm really trying to do is add up the values from ting[0-24] that comes AFTER the second comma. This made me try to do a split but that does not work
You already have a list; the commas are put there by Python to delimit the values only when printing the list.
Just access element 2 directly:
print ting[2]
This prints:
[1379962800000, 125.539504822835]
Each of the entries in item['values'] (so ting) is a list of two float values, so you can address each of those with index 0 and 1:
>>> print ting[2][0]
1379962800000
>>> print ting[2][1]
125.539504822835
To get a list of all the second values, you could use a list comprehension:
second_vals = [t[1] for t in ting]
When you load the data with json.loads, it is already parsed into a real list that you can slice and index as normal. If you want the data starting with the third element, just use ting[2:]. (If you just want the third element by itself, just use ting[2].)
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.