1

I'm trying to figure out how many numbers in a text file are larger than 0.1. The text file has 1001 last names and numbers in the following format:

Doe 5
Anderson 0.3
Smith 6

I figured out how to separate the numbers but i'm having trouble converting my string of numbers into a list so that I can then compare them to 0.1

Here is what I have so far:

    infile = open('last.txt')
    lines = infile.readlines()
    for line in lines:
        items = line.split()
        nums = (items[1])

also, once I have my list, how do I go about comparing it to 0.1?

3 Answers 3

4

Supposing lines is a list of strings, and each of them consists of exactly one number and nothing more.

result = sum(1 if float(x) > 0.1 else 0 for x in lines)

Another very similar way to do the same:

result = sum(float(x) > 0.1 for x in lines)
Sign up to request clarification or add additional context in comments.

Comments

0

From your description, and code snippet, you seem to have a file that has a space separated name an number like so:

Name1 0.5
Name2 7
Name3 11

In order to get a sum of how many number are greater than 0.1, you can do the following:

result = sum(float(line.split()[1]) > 0.1 for line in lines)

Comments

0

The other answers tell you how to count the occurrences which are greater than 0.1, but you may want to have the numbers in a list so that they can be used for other purposes. To do that, you need a small modification to your code:

with open('last.txt', 'r') as infile:
    lines = infile.readlines()

nums = []
for line in lines:
    items = line.split()
    nums.append(float(items[1]))

This gives you a list nums of all of the numbers from your file. Note that I have also used the Python context manager (invoked with with) to open the file which ensures that it is closed properly once you are no longer using it.

Now you can still count the occurrences of values larger than 0.1 in nums:

sum(1 if x > 0.1 else 0 for x in nums)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.