Python - 读取文件并计算重复元素

时间:2017-10-08 08:35:50

标签: python file class for-loop

我有一个包含这样的数字列表的文本文件:
1
2 5 3
3 5
4
5
每个数字都是树的节点。如果一行中有多个数字,则表示第一个数字的后面跟着数字 1之后没有任何数字,因此它没有任何数字链接。
2有3个和5个链接。
3有5个链接到它并且它自己变为2。
4没有任何数字链接。
5没有与之关联的任何数字,但它与3和2相关联。
由于2,3和5连在一起,它们形成一个组成部分。 1和4没有链接,没有数字链接,因此它们各自组成一个组件 因此,总共有3个组成部分 您如何确定组件数量? 我在 for 循环和条件方面遇到了困难。

def components(self):
    elm = 0
    with open('file.txt','r') as f:
        for line in f:
            comp = list(line)
            for x in comp:
                if comp[x] != comp[x+1]:
                    elm += 1
                else:
                    pass
    print(elm)

我尝试了上面的代码。但是,当我运行它时,我在函数执行中得到了下一条消息:

 components missing 1 required positional argument: 'self'

可能有必要提一下我正在上课,而我对这些事情几乎不熟悉。

1 个答案:

答案 0 :(得分:1)

您使用for-loops以正确的方式进行此操作,但您似乎对loop通过的内容感到困惑!如果我理解你想要正确实现的目标,我想我已经编写了代码写入以正常工作。

使用名为text的{​​{1}}文件,内容为:

file.txt

以下代码将创建1 253 35 4 5 list,然后components创建最后printcomponents

components = []
with open("file.txt", "r") as f:
    for line in f:
        line = [int(i) for i in line.strip()]
        newComponent = True
        for comp in components:
            if not newComponent:
                break
            for ele in line:
                if ele in comp:
                    comp += line
                    newComponent = False
                    break
        components = [list(set(c)) for c in components]
        if newComponent:
            components.append(line)

print(len(components))

输出你想要的东西:

3

代码首先将text文件打开到f。然后我们开始我们的第一个loop,它将遍历line中的每个file。我们使用line上的list将此ints转换为list-comprehension line.strip() .strip()只删除new-line {{ 1}}从最后开始。

然后我们定义char - bool - 初始化为newComponents,因为我们假设此True没有line

接下来,我们通过links loop中的每个component list。我们在这里做的第一件事就是快速检查我们之前是否已找到components componentline的{​​{1}}。如果有,我们只需linked break。{/ p>

否则,如果我们尚未loop,我们会浏览linked中的每个element,并检查lineelement是否在component我们目前looping。如果是,我们concatenate(使用+)我们的line加上componentbool newComponent flag由于我们找到了break,因此loop中的linkcomponents = [list(set(c)) for c in components]

在此之后,行duplicates只会浏览组件并从每个链接中删除3。例如,如果23相关联,而我们之前已将5component添加到2,则现在会3s } component中的duplicates - 重复。这一行只删除了那些components。严格来说,这条线是没有必要的,因为我们仍然会得到相同的结果,但我只是认为如果你想稍后使用links,它会占用代码。

最后,如果找不到newComponentTrue仍为line),我们只需将整个linked(因为它们是components)附加到list print()

就是这样!我们len()结尾处有file.txt的长度,您可以得到结果。

希望这对你有用!

更新

如果space的内容是包含多个数字的数字,则可以将其与11 2 45 45 67 8 91 分开:

.split()

然后我们要做的就是在list-comprehension的末尾添加components = [] with open("file.txt", "r") as f: for line in f: line = [int(i) for i in line.strip().split(' ')] ...

string

这样做是line的{​​{1}}而不是looping通过char中的每个string,我们会{{1}来自list的每个splittingstring的{​​{1}}。{}为了证明这一点:

space

给出:

iterate