My list is ['1','2','to','3']
I need to write a logic that
- convert '1' '2' which is string to 1, 2 which is integer
- print an error msg since 'to' string is included and cannot be converted to integer
Here's the code I have right now:
def average_file(filename):
inputFile = open(filename, "r")
inList = []
results = []
n = []
for line in inputFile:
inList.append(line.strip()) #inList.append(line)
n = [int(elem) for elem in inList if elem.isdigit()] #I only remove the string and leave integer in my list, but I need a check logic to print error msg
results = list(map(int, n))
inputFile.close()
results = sum(results)/len(results)
return results
5 Answers 5
Few things:
- The pythonic way to do it is to expect it to be an all digit value and handle the error when it is not.
- You can use
with
to handle your file lifetime. - You can calculate sum and count of elements during the reading without saving additional array (and therefore know the average).
strip
is redundant when parsing toint
like thatint(variable)
:
There you go:
def average_file(filename):
summary = 0
count = 0
with open(filename, "r") as inputFile:
for line in inputFile:
try:
summary += int(line)
count += 1
except ValueError as e:
print('Can not parse "{0}" to a number'.format(line))
# If reached here one of the values in the file is not a number and None is returned immediately
return None
# If count is 0 return None, otherwise return the average
return (summary / count) if count else None
The answer was edited after some clarifications from OP:
Immediately return None
when one of the values is not a number.
-
I input a test file (.txt) with string. I expect the error msg. However, it returned the float 51.22222222222222. the below is the content of my testing file 1 2 3 4 5 wut 6 7 8 9potentialwjy– potentialwjy2018年12月20日 16:23:25 +00:00Commented Dec 20, 2018 at 16:23
-
@potentialwjy It makes no sense the average from my code came out
51.222
from input that the maximum value was9
. Something else is wrong there. For the array[1, 2, 3, 4, 5, 'wut', 6, 7, 8, 9]
the result will be5
and on the console you will seeCan not parse "wut" to a number
.Maor Refaeli– Maor Refaeli2018年12月20日 16:30:58 +00:00Commented Dec 20, 2018 at 16:30 -
@potentialwjy Is each value on the file is in a new line?Maor Refaeli– Maor Refaeli2018年12月20日 16:34:08 +00:00Commented Dec 20, 2018 at 16:34
-
my fault, I used the testing file in the class which is invisible..Now I use my testing file 1,2,3...wut...9, it shows: Can not parse "wut " to a number Out[192]: 5.0 the expectation is to have the error msg only. It should not have the 5.0 as average in this case. Any thought? Thanks for your help!potentialwjy– potentialwjy2018年12月20日 16:42:28 +00:00Commented Dec 20, 2018 at 16:42
-
@potentialwjy I edited my answer (added a
return None
at theexcept
handler), have a lookMaor Refaeli– Maor Refaeli2018年12月20日 16:49:37 +00:00Commented Dec 20, 2018 at 16:49
convert '1' '2' which is string to 1, 2 which is integer print an error msg since 'to' string is included and cannot be converted to integer
source = ['1', '2', 'to', '3']
result = []
for item in source:
try:
result.append(int(item))
except ValueError as ex:
print('Not integer: {}'.format(item))
print(result)
-
Agree, just have written
ex
mechanicallygrapes– grapes2018年12月20日 16:30:52 +00:00Commented Dec 20, 2018 at 16:30
Attempt to convert each item to the list of results. If the conversion fails, print an error message.
l = ['1','2','to','3']
result = []
for item in l:
try:
result.append(int(item))
except ValueError:
print(item)
You can use a try
/except
block to separate the valid integer literals from everything else:
candidates = ['1','2','to','3']
for candidate in candidates:
try: # attempt the conversion
value = int(candidate)
except ValueError: # conversion failed!
print(candidate, 'is not an integer')
else: # conversion succeeded
print(candidate, 'is the integer', value)
In your case, you can just collect the values in the else
clause:
results = []
with open(filename) as input_file:
for line in inputFile:
try:
value = int(line.strip())
except ValueError:
print(line.strip(), 'is not an integer')
else:
results.append(value)
-
your solution almost works...but my testing result shows: wut is not an integer 5.0 my testing file is a txt with below info: 1 2 3 4 5 wut 6 7 8 9potentialwjy– potentialwjy2018年12月20日 16:37:20 +00:00Commented Dec 20, 2018 at 16:37
l = ['1', '2', 'word', '4']
You can do:
n = [int(i) if i.isdigit() else print('\nNot able to convert: '+i) for i in l]
Output:
Not able to convert: word
l = [1, 2, None, 4]
-
2Wouldn't that add
None
elements ton
... 🤔 Edit: I'm getting a syntax error forelse print
.TrebledJ– TrebledJ2018年12月20日 16:05:21 +00:00Commented Dec 20, 2018 at 16:05 -
I don't think
print
statements are suitable for list comprehensions.RoadRunner– RoadRunner2018年12月20日 16:26:59 +00:00Commented Dec 20, 2018 at 16:26 -
Yeah you are right. I should have tried it, I'll modify itFrancesco Pegoraro– Francesco Pegoraro2018年12月20日 16:39:01 +00:00Commented Dec 20, 2018 at 16:39
results
every time a line is read? (It's not exactly wrong, but it's fishy.)