Python 为什么set不计算我的唯一整数?

Python 为什么set不计算我的唯一整数?,python,python-2.7,set,Python,Python 2.7,Set,我昨晚刚刚开始通过Python文档、教程等问题自学Python 到目前为止,我可以向用户请求一个文件,打开并读取该文件,删除文件中的所有和开头\n,将每行读取到一个数组中,并计算每行的整数数 我想计算每行的唯一整数数。我意识到Python使用了一个set功能,我认为这个功能在这个计算中非常有效。但是,我始终会收到一个大于我将向您显示的先前值的值。我查看了其他与sets相关的SO帖子,没有看到我没有遗漏的内容,并且有一段时间被难住了 代码如下: with open(filename, 'r') a

我昨晚刚刚开始通过Python文档、教程等问题自学Python

到目前为止,我可以向用户请求一个文件,打开并读取该文件,删除文件中的所有和开头\n,将每行读取到一个数组中,并计算每行的整数数

我想计算每行的唯一整数数。我意识到Python使用了一个set功能,我认为这个功能在这个计算中非常有效。但是,我始终会收到一个大于我将向您显示的先前值的值。我查看了其他与sets相关的SO帖子,没有看到我没有遗漏的内容,并且有一段时间被难住了

代码如下:

with open(filename, 'r') as file:
    for line in file:
        if line.strip() and not line.startswith("#"):
            #calculate the number of integers per line
            names_list.append(line)
            #print "There are ", len(line.split()), " numbers on this line"

            #print names_list

           #calculate the number of unique integers
            myset = set(names_list)
            print myset
            myset_count = len(myset)
            print "unique:",myset_count
进一步解释如下:

名单如下:

['1 2 3 4 5 6 5 4 5\n', '14 62 48 14\n', '1 3 5 7 9\n', '123 456 789 1234 5678\n', '34 34 34 34 34\n', '1\n', '1 2 2 2 2 2 3 3 4 4 4 4 5 5 6 7 7 7 1 1\n']
我的_集是:

set(['1 2 3 4 5 6 5 4 5\n', '1 3 5 7 9\n', '34 34 34 34 34\n', '14 62 48 14\n', '1\n', '1 2 2 2 2 2 3 3 4 4 4 4 5 5 6 7 7 7 1 1\n', '123 456 789 1234 5678\n'])
我收到的输出是:

unique: 1
unique: 2
unique: 3
unique: 4
unique: 5
unique: 6
unique: 7
应该发生的输出是:

unique: 6
unique: 3
unique: 5
unique: 5
unique: 1
unique: 1
unique: 7
关于为什么我的每行集合没有计算每行唯一整数的正确数目,有什么建议吗?如果你愿意的话,我还想听听关于如何改进我的代码的建议,因为我昨晚刚开始自学Python,我很喜欢这些技巧。多谢各位

myset = set(names_list)
应该是

myset = set(line.split())
应该是

myset = set(line.split())

问题是,当您在文件上迭代时,您会将每一行附加到列表名称\u列表中。在那之后,你要用这些线建立一个集合。您的文本文件似乎没有任何重复的行,因此打印集合的长度只会显示您已处理的当前行数

下面是一个注释修复:

with open(filename, 'r') as file:
    for line in file:
        if line.strip() and not line.startswith("#"):
            numbers = line.split() # splits the string by whitespace and gives you a list
            unique_numbers = set(numbers) # builds a set of the strings in numbers
            print(len(unique_numbers)) # prints number of items in the set

请注意,我们正在使用当前处理的行,并在拆分行后从中构建一个集合。原始代码存储所有行,然后根据每个循环中的行构建一个集合。

问题在于,当您在文件上迭代时,会将每行附加到列表名称中。在那之后,你要用这些线建立一个集合。您的文本文件似乎没有任何重复的行,因此打印集合的长度只会显示您已处理的当前行数

下面是一个注释修复:

with open(filename, 'r') as file:
    for line in file:
        if line.strip() and not line.startswith("#"):
            numbers = line.split() # splits the string by whitespace and gives you a list
            unique_numbers = set(numbers) # builds a set of the strings in numbers
            print(len(unique_numbers)) # prints number of items in the set

请注意,我们正在使用当前处理的行,并在拆分行后从中构建一个集合。原始代码存储所有行,然后根据每个循环中的行构建一个集合。

谢谢您的解释。我做了些改变,一切都很顺利。谢谢你的解释。我做了些改变,一切都很顺利。谢谢,谢谢。谢谢,谢谢。我很感激。