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

标签 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,并且希望得到提示。谢谢。

最佳答案

问题在于,当您遍历文件时,您将每一行附加到列表 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

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

关于python - 为什么 set 不计算我的唯一整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34977363/

相关文章:

android - SharedPreferences 字符串设置为数组顺序问题

python - Flask SQLAlchemy 批量删除记录

python - 跨多列实现 Django 2.2 数据库约束

python - Numpy maskedarray 缺少堆栈函数

python:在函数内表现不佳的dict-错误的TypeError

Python:frozensets 比较

python - 检查 object_id 在 queryset.annotate Case When 参数中是否出现多次

python - 不使用本地主机连接 MySQL

Python JSONPath 过滤器表达式错误,jsonpath-rw 1.4.0 的意外字符

c++ - 迭代计算集合或 vector 的幂集