Python: Appending to array which doesn't exists yet - python

I'm trying to add items to 2D array "groups". I'm getting error. I know why, but I don't know how to solve it. I tried groups[1].add but it did not work. The array groups[1] doesnt exists when I am trying to append. Is there a way, how to make this array only when it is necessary (when trying to append or add or insert)?
def sortResults(results,pattern):
ordered=results
ordered.sort()
groups= [[]]
for r in results:
print r
tuple=evaluate(pattern,r)
print(tuple)
if tuple[0]==1:
groups[0].append(r)
elif tuple[0]==2:
groups[1].append(r)
for group in groups:
print(group)
for item in group:
if item != 0:
ordered.remove(item)
ordered.append(item)
return ordered
I'm getting this error:
groups[1].append(r)
IndexError: list index out of range
Thanks in advance!

Why not use:
groups = [[], []]
instead if you are going to append to two groups? Then you won't run into that problem.
You can always remove it again if it remains empty, or you can use exception handling:
elif tuple[0]==2:
try:
groups[1].append(r)
except IndexError:
groups.append([r])
as the list missing is only a problem once.

Related

How do I print specific items from a python list?

I am trying to print multiple items from a list in Python. I have looked at many examples but I am unable to get them to work. What is a good way to print items from the imported list based on their list index.
The commented out example in my code is what I thought will work and cant find a simple solution.
items = []
with open('input.txt') as input_file:
for line in input_file:
items.append(line)
print(items[5],items[6])
#print(items[5,6,7]
One way to do it would be with a for loop.
item_list = ['a','b','c','d','e','f','g','i'] # an example list.
index_to_print = [5,6,7] # add all index you want to print to this list.
for i in item_list:
if item_list.index(i) in index_to_print:
print(i)
update: instead of looping through the whole item_list, we can loop through the indexes you want to print.
for i in index_to_print:
if i < len(item_list):
print(item_list[i])
else:
print('given index is out of range.')

if an item in a list doesn't match a column name in a data frame, produce exception statement

I have the following code which creates a list, takes inputs of column names the user wants, then a for loop applies each list attribute individually to check in the if statement if the user input matches the columns in the data frame.
Currently this produces an exception handling statement if all inputs to the list are unmatching, but if item in the list matches the column in the dataframe but others do not, then jupyter will produce its own error message "KeyError: "['testcolumnname'] not in index", because it is trying to move onto the else part of my statement and create the new dataframe with this but it cant (because those columns do not exist)
I want it to be able to produce this error message 'Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.' if even 1 inputted list attribute does not match the dataframe and all other do. But Ive been struggling to get it to do that, and it produces this KeyError instead.
My code:
lst = []
lst = [item for item in str(input("Enter your attributes here: ")).lower().split()]
for i in lst:
if i not in df.columns:
print('Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.')
break
else:
df_new = df[lst]
# do other stuff
for example if i have a dataframe:
A
B
C
NA
yes
yes
yes
no
yes
and my list contains:
['A','B','C']
It works correctly, and follows the else statement, because all list items match the dataframes columns so it has no problem.
Or if it has this:
['x','y','z']
It will give the error message I have, correctly. Because no items match the data frames items so it doesn't continue.
But if it is like this, where one attribute is matching the dataframe, and others not...
['A','D','EE']
it gives the jupyter KeyError message but I want it to bring back the print message i created ('Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.').
The KeyError appears on the line of my else statement: 'df_new = df[lst]'
Can anyone spot an issue i have here that will stop it from going this? Thank you all
Try not to print, but to raise exception
And you need to fix your indentation
lst = []
lst = [item for item in str(input("Enter your attributes here: ")).lower().split()]
for i in lst:
if i not in df.columns:
raise ValueError('Attribute does not exist in Dataframe. Make sure you have entered arguments correctly.')
df_new = df[lst]
# do other stuff

python - list comprehensions including conditions like if and else/ error handling

is there a neat way to include conditions in list comprehensions in order to do the following:
index = [y for y, s in enumerate(data_time_filtered) if next0 in s]
I'd like to add the following conditions in the index definition above:
if next0 in s:
data_filtered.append(data_time_filtered[index[0]])
else:
missing_data.append(next0)
currently what's happening in my code is:
IndexError: list index out of range
when the value can not be found. Is it more efficient to handle it with else and if conditions or is there another / better way for error handling in this case?
EXTENSION:
data_time_filtered is a list of strings like:
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.A2018002.1330.006.2018003152138.hdf
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/004/MYD021KM.A2018004.1330.006.2018005220236.hdf
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/006/MYD021KM.A2018006.1330.006.2018007165439.hdf
https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/009/MYD021KM.A2018009.1330.006.2018010190624.hdf
next0 are strings in the form of: /XXX/ for example /002/
The index function is looking for the line in data_time_filtered where next0 appears and is returning a index which is used in order to extract that line and append it to a different list.
The problem is that sometimes, the string given by next0 is not contained in the list creating the error message above.
What I would like is:
If index comes a cross such a number it should append this number in a missing_data list instead of breaking and producing the error.
UPDATE:
i tried this:
try:
index = [y for y, s in enumerate(data_time_filtered) if next0 in s]
data_filtered.append(data_time_filtered[index[0]])
except IndexError:
missing_data.append(next0)
and it worked :). However, in a later stage on a different line an IndexError is occurring. still checking how to sort this out
I don't quite get what you're trying to do with this code, but maybe this will get you a bit closer.
index = [data_filtered.append(data_time_filtered[s]) if next0 in s else missing_data.append(next0) for s in data_time_filtered]
I have tried to get your requirement - Let me know if the below code helps or not,
data_time_filtered = [
'https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/002/MYD021KM.A2018002.1330.006.2018003152138.hdf',
'https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/004/MYD021KM.A2018004.1330.006.2018005220236.hdf',
'https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/006/MYD021KM.A2018006.1330.006.2018007165439.hdf',
'https://ladsweb.modaps.eosdis.nasa.gov/archive/allData/6/MYD021KM/2018/009/MYD021KM.A2018009.1330.006.2018010190624.hdf']
# combinations of exist & non-exist values
next0_list = ['/002/', '/004/', '/111/', '/222/']
data_filtered = list()
missing_data = list()
# for next0 in next0_list:
# index = [data_filtered.append(s) for s in data_time_filtered if next0 in s]
# if not index:
# missing_data.append(next0)
index = [missing_data.append(next0) for next0 in next0_list if
not [data_filtered.append(s) for s in data_time_filtered if next0 in s]]
print(missing_data)
print(data_filtered)
Instead of putting the conditions into the definition of index, it turns out that the error handling like:
try:
index = [y for y, s in enumerate(data_time_filtered) if next0 in s]
data_filtered.append(data_time_filtered[index[0]])
except IndexError:
missing_data.append(next0)
is more practical as one can include further conditions or loops in the except IndexError part.

Return an index of a string stored in an array

I have an array and an input, if I input something I want to use .startswith() with my array, for example if I have this:
Array = ['foo','bar']
And if I input "fo" I want it to match it with "foo" and then return the index, in this case 0. How would I do this?
MaryPython's answer is generally fine. Alternatively, in O(n) instead of O(n^2), you could use
for index, item in enumerate(my_list):
if item.startswith('fo'):
print(index)
I've used enumerate to walk the index with the item
Note that Marky's implementation fails on this array
['fo','fo','fobar','fobar','hi']
because .index always returns the first instance of a repeated occurrence (but otherwise his solution is fine and intuitive)
Here is one solution. I iterated through the list and for each item checked if they start with the string 'fo' (or whatever your want to check with). If it starts with that string it prints the index of that item. I hope this helps!
Array = ['foo', 'bar']
for item in Array:
if item.startswith('fo'):
print(Array.index(item))
#!/usr/bin/python
# -*- coding: ascii -*-
Data = ['bleem', 'flargh', 'foo', 'bar' 'beep']
def array_startswith(search, array):
"""Search an iterable object in order to find the index of the first
.startswith(search) match of the items."""
for index, item in enumerate(array):
if item.startswith(search):
return(index)
raise(KeyError)
## Give some sort of error. You probably want to raise an error rather
## than returning None, as this might cause a logic error in the
## later program. I think KeyError is correct, based on the question.
## See Effective Python by Brett Slatkin, Page 29...
if __name__ == '__main__':
lookfor='fo'
try:
result=array_startswith(lookfor, Data)
except KeyError as e:
print("'{0}' not found in Data, Sorry...".format(lookfor))
else:
print("Index where '{0}' is found is: {1}. Found:{2}".format(lookfor,
result, Data[result]))
finally:
print("Try/Except/Else/Finally Cleanup happens here...")
print("Program done.")

index error while running a loop over list contents

I have a list like this:
my_array= ["*","device",":","xyz"], ["+","asd","=","10","pdf","=","6"],
["+","dsa","=","1","pqa","=","2","dga","=","12"], ["*"]
What I want to do is:
define('device','xyz')
define('asd','10')
define('pdf','6')
define('dsa','1')
define('pqa','2')
define('dga','12')
The way I approached is:
i=0
while i < len(my_array):
if my_array[i][0]=="*":
print("'",my_array[i][1],"'","'",my_array[i][3:],"'")
elif my_array[i][0]=="+":
print("'",my_array[i][1],"'","'",my_array[i][3],"'")
if my_array[i][4]=="\D":
print("'",my_array[i][4],"'","'",my_array[i][6],"'")
elif my_array[i][7]=="\D":
print("'",my_array[i][7],"'","'",my_array[i][9],"'")
i=i+1
But doing this, I get index error. I know where the problem is, but I cannot fix it with my very bad programming brain. Can someone help me on this?
First review problem seems in
if my_array[i][0]=="*":
print("'",my_array[i][1],"'","'",my_array[i][3:],"'")
because last element in your my_array is ['*'] and it has no other elements and u are trying to access my_array['*'][1] and its give index error.
You have to remove that element or add members who fulfill element index requirement.
Hard-coding the indices is a sure sign you're doing something wrong - the items in my_array have variable lengths, so some of your indices inevitably fail. I think what you want is something like:
for command in my_array:
if command[0] in ("*", "+"):
for start in range(1, len(command), 3):
assignment = command[start:start+3]
if assignment[1] in ("=", ":"):
print assignment[0], assignment[2]
It is worth noting, however, that you seem to be attempting to write a file parser. Although this code solves this specific problem, it is likely that your overall approach could be improved.
With the assumption, that every key in your list has a value attached to it(e.g. there are no two asterisk following after each other) you can make some simplifications:
We'll read the first value as a key of a new dict and the second item as the value.
With the newly tidied up dict(d) you can continue to work easily e.g. in a for loop:
array=["*","device",":","xyz"], ["+","asd","=","10","pdf","=","6"],
["+","dsa","=","1","pqa","=","2","dga","=","12"], ["*"]
d = {}
for list in array:
new_key = None
for item in list:
if item in ['*',':','+','=']: continue
if new_key == None:
new_key = item
else:
d[new_key] = item
new_key = None
for key in d:
define(key,d[key])

Categories