for i in range(0,len(text_list)):
if (text_list[i] == "!" and text_list[i+1].isupper()):
print "something"
else:
text_list.pop(i)
Traceback (most recent call last):
File "test.py", line 12, in <module>
if (text_list[i]=="!" and text_list[i+1].isupper()):
Error:
IndexError: list index out of range
I want to remove all the exclamation marks from a text file that are not at the end of a sentence.
When i becomes len(text_list) - 1, i + i is out of bounds. This is your first problem. The second problem is that you are popping within the for loop. This changes the size of the list.
I suggest to save the indices to be removed in a separate list, and then pop them after the loop is finished.
to_remove = []
for i in range(0,len(text_list) - 1):
if (text_list[i]=="!" and text_list[i+1].isupper()):
print "something"
else:
to_remove.append(i)
for i in reversed(to_remove):
text_list.pop(i) # use del if you don't need the popped value
When your i will become last index of the text_list then "text_list[i+1].isupper()" will give you error because i+1 will be out of index range. You can do something like this :
for i in range(0,len(text_list)):
if(i!=len(text_list-1)):
if (text_list[i]=="!" and text_list[i+1].isupper()):
print "something"
else:
text_list.pop(i)
Related
In python 3.10 I created a function that generates a list with 6 integers.
I want to print the list of integers within a string, including brackets, but without spaces.
def create_grid(number):
n = number
return [n, n+2, n+4, n+1, n+3, n+5]
l = create_grid(0)
print(l)
[0, 2, 4, 1, 3, 5]
type(l)
<class 'list'>
Desired output: "text prepend [0, 2, 4, 1, 3, 5] text append"
I've tried it with join as suggested in 17190709
print('[{0}]'.format(','.join(map(str, l))))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Other methods complain the list elements are integers, not the expected string. Or print it with spaces anyway.
The one way I could get working was calling each element in f-string
print(f'text prepend [{l[0]},{l[1]},{l[2]},{l[3]},{l[4]},{l[5]}] text append')
text prepend [0,2,4,1,3,5] text append
I've been scratching my head for a better option, curious if any of you can come up with one.
Thanks in advance!
I have a code that I am trying to run which will compare a value from a csv file to a threshold that I have set within the py file.
My csv file has an output similar to below, but with 1030 lines
-46.62
-47.42
-47.36
-47.27
-47.36
-47.24
-47.24
-47.03
-47.12
Note: there are no lines between the values but there is a single space before them.
My first attempt was with this code:
file_in5 = open('710_edited_capture.csv', 'r')
line5=file_in5.readlines()
a=line5[102]
b=line5[307]
c=line5[512]
d=line5[717]
e=line5[922]
print[a]
print[b]
print[c]
print[d]
print[e]
which gave the output of:
[' -44.94\n']
[' -45.06\n']
[' -45.09\n']
[' -45.63\n']
[' -45.92\n']
My first thought was to use .strip() to remove the space and the \n but this is not supported in lists and returns the error:
Traceback (most recent call last):
File "/root/test.py", line 101, in <module>
line5=line5.strip()
AttributeError: 'list' object has no attribute 'strip'
My next code below:
for line5 in file_in5:
line5=line5.strip()
line5=file_in5.readlines()
a=line5[102]
b=line5[307]
c=line5[512]
d=line5[717]
e=line5[922]
print[a]
print[b]
print[c]
print[d]
print[e]
Returns another error:
Traceback (most recent call last):
File "/root/test.py", line 91, in <module>
line5=file_in5.readlines()
ValueError: Mixing iteration and read methods would lose data
What is the most efficient way to read in just 5 specific lines without any spaces or \n, and then be able to use them in subsequent calculations such as:
if a>threshold and a>b and a>c and a>d and a>e:
print ('a is highest and within limit')
CF=a
You can use strip(), but you need to use read() instead of readlines(). Another way, if you have more than one value in a row with comma separation, you can use the code as below:
with open('710_edited_capture.csv', 'r') as file:
file_content=file.readlines()
for line in file_content:
vals = line.strip().split(',')
print(vals)
You can also append "vals" to an empty list. As a result, you will get a list that contains a list of values for each line.
it's a little bit unclear what you want to do but if you just want to read a file compare each value to a threshold value and keep upper value here a example :
threshold=46.2
outlist=[]
with open('data.csv', 'r') as data:
for i in data:
if float(i)>threshold:
outlist.append(i)
then you can adapt it to your needs...
Thanks for all the comments and suggestions however they are not quite what I needed.
I have however applied a workaround, although admittedly clunky.
I have created 5 additional files from the original with only the one value in each. From this I can now strip the space and /n and save them locally as a variable. I no longer needed the readlines
These variables can be compared to each other and the threshold to determine the optimum choice.
def func():
import csv
file=open("cmiday.csv")
x,y=[],[]
reader=csv.DictReader(file)
for row in reader:
if(type(row["max_rel_hum"])%1==0):
continue
if(type(row["precip"])%1==0):
continue
if(row["max_rel_hum"]>100):
continue
if(row["max_rel_hum"]<0):
continue
if (row["precip"]>10):
continue
if(row["precip"]<0):
continue
x.append(row["max_rel_hum"])
y.append(row["precip"])
print x
print y
I'm trying to collect data from a csv file into lists x and y. I don't want any values for row["max_rel_hum"] to be integers or be more than 100 or less than 0. Similarly, I don't want any values for row["precip"] to be more than 10 or less than 0. I'm getting this error when I try to run the function:
>>> func()
Traceback (most recent call las
File "<stdin>", line 1, in <m
File "hw.py", line 7, in func
if(row["max_rel_hum"]%1==0)
ValueError: incomplete format
Please help out. Thanks
Values from a CSV are strings, not integers. You're expecting % to do modulo, but on a string it does string formatting.
You need something like this:
if ( int(row["max_rel_hum"]) % 1 == 0):
And you need to do int() for in all the lines, even the < and > ones - they are valid operations on strings, but will do an alphabetical order comparison, not a numeric comparison, and won't give the results you expect.
You don't need type() in the if line at all.
I wrote the following. My goal was to try and create a robust way for the code to read sentences for a text-adventure game. I made lists (h_answer1 and 2) populated with the keywords I wanted the game to recognize, and then I asked for user input in the mansr function (mansr takes its argument and makes it lower case), and then I split that input into a list called split_ans.
This works about half the time. But if I input certain phrases, like "I believe I will search," it throws me through the else statement, even though "search" appears in my sentence.
If I understand correctly, the for-loop is setting check equal to each string in the split_ans list, and then the if-statement is checking to see if that particular check matches anything in the h_answer lists. So why would python go to the else statement when the if condition has been met?
def some_function():
print "some stuff"
ans = mansr(raw_input())
split_ans = ans.split(' ')
h_answer1 = ['walk', 'run', 'go']
h_answer2 = ['search', 'look']
for check in split_ans:
if check in h_answer1:
print "Some stuff"
break
elif check in h_answer2:
print "Some stuff"
ans = mansr(raw_input(' '))
split_ans = ans.split(' ')
<section omitted, it's a nested for-loop>
else:
print "I don't understand that input."
some_function()
The traceback doesn't reveal much (some_function was named long_hallway, edited above in order to be more generic):
File "test06.py", line 171, in <module> start()
File "test06.py", line 92, in start long_hallway()
File "test06.py", line 59, in long_hallway long_hallway()
File "test06.py", line 59, in long_hallway long_hallway()
File "test06.py", line 13, in long_hallway
ans = mansr(raw_input('\n>>> '))
That traceback is pretty unininformative. What was the associated exception?
One obvious source of possible problems is that you're re-using the ans and split_ans variables. Since you are iterating on split_ans you may run into issues because you're trying to change it in mid execution, which is a no-no.
The other thing is - are you sure you want a break rather than a continue? Do you want to escape the parsing loop after the first hit?
if emp in like_list[j]:
TypeError: coercing to Unicode: need string or buffer, list found
Both emp and like_list are lists containing strings.
Because both emp and like_list are lists, you are essentially looking for a list within a list.
If you're trying to match any element within list emp, you can iterate over the list like this:
for element in emp:
if element in like_list:
--do something--
else:
--do something else--
Alternatively, if like_list were a list of lists, your if statement would work.
If both emp and like_list are lists of strings, the expression emp in like_list[j] is checking if a list is a member of a single string. When I tested it out with the code below I got a slightly different TypeError:
>>> emp = ["foo", "bar"]
>>> like_list = ["baz", "quux"]
>>> if emp in like_list[0]:
... print "found"
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
This says that you can't test non-strings for membership in a string. I think fixing this will be pretty easy, but it's not entirely clear what you were trying to do.
If you want to check if the string like_list[j] has one of the strings in emp as a substring, use:
if any(s in like_list[j] for s in emp):
If instead you want to see if like_list[j] is equal to one of the strings in emp, you need to turn around the in expression:
if like_list[j] in emp: