简体   繁体   English

如何在 Python 上将一串数字转换为列表?

[英]How do I turn a string of numbers into a list on Python?

I'm trying to figure out how many numbers in a text file are larger than 0.1.我想弄清楚文本文件中有多少个数字大于 0.1。 The text file has 1001 last names and numbers in the following format:文本文件有 1001 个姓氏和数字,格式如下:

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我想出了如何分隔数字,但我在将数字字符串转换为列表时遇到问题,以便我可以将它们与 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?另外,一旦我有了我的清单,我该如何将它与 0.1 进行比较?

Supposing lines is a list of strings, and each of them consists of exactly one number and nothing more.假设lines是一个字符串列表,每个字符串只包含一个数字,仅此而已。

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)

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:为了得到多少个数字大于 0.1 的总和,您可以执行以下操作:

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

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.其他答案告诉您如何计算大于 0.1 的出现次数,但您可能希望将数字列在列表中,以便将它们用于其他目的。 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.这给你一个列表nums所有号码从您的文件。 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.请注意,我还使用了Python上下文管理器(与调用with )来打开它保证一旦你不再使用它,它正确地关闭该文件。

Now you can still count the occurrences of values larger than 0.1 in nums :现在您仍然可以计算nums大于 0.1 的值的出现次数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM