为什么设置不计算我的唯一整数?

时间:2016-01-24 15:09:26

标签: python python-2.7 set

我昨晚通过Python文档,教程和SO问题开始自学Python。

到目前为止,我可以向用户询问文件,打开并读取文件,删除文件中的所有#和开头\ n,将每行读入数组,并计算每行的整数数。

我想计算每行的唯一整数数。我意识到Python使用了一种我认为可以完美地用于此计算的集合功能。但是,我总是收到一个大于先前值的值(我会告诉你)。我查看了与集合相关的其他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

进一步说明:

names_list是:

['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']

和my_set是:

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并且很喜欢提示。谢谢。

2 个答案:

答案 0 :(得分:3)

问题在于,当您迭代文件时,您将每行附加到列表names_list。之后,您将构建这些行中的一组。您的文本文件似乎没有任何重复的行,因此打印集合的长度只显示您已处理的当前行数。

这是一个注释修复:

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

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

答案 1 :(得分:2)

myset = set(names_list)

应该是

myset = set(line.split())