Reputation: 45
I have a text file in python jupyter notebook. The questions is asking 'Count the numbers larger than 0.1.' I do not know how to write a code for this. The text file has names and integers. I think I can create two lists for this, but not sure what how to get the output for the numbers larger than .1.
This is the code that I have written so far.
def ans9(file):
infile = open(file)
contents = infile.read().split()
infile.close()
Upvotes: 2
Views: 387
Reputation: 3265
I don't agree with tgikal's use of lists-of-lists. The correct data structure in this case is probably a dictionary (yes indentations look funny but PEP-8 compliant and if you ignore them it reads like English) :
filename = 'people.txt'
with open(filename) as file:
filtered_users = {user:score
for user, score in (line.split()
for line in file
if line)
if score > 0.1}
print(len(filtered_users))
Upvotes: 0
Reputation: 1680
If all you need is a count of them, something like this would work:
def ans9(file):
with open(file, 'r') as infile:
count = 0
for line in infile:
if float(line.split('\t')[1]) > 0.1:
count += 1
return count
If you want a split up representation of the data:
def ans9(file):
with open(file, 'r') as infile:
items = []
for line in infile:
item = line.split('\t')
if float(item[1]) > 0.1:
items.append(item)
return items
Would return a list that looks like [["a", "0.22"], ["b", "0.11"]]
and you could iterate through it fairly easily.
Upvotes: 1
Reputation: 2882
with open('a.txt', 'r') as f:
data = []
for line in f:
data.append(float(line.split()[1]))
print(len([i for i in data if i > 0.1]))
# prints 2 for the following data:
Smith 0.88
Johnson 0.68
Brown 0.04
Upvotes: 0