【问题标题】:Compare list from file with multiples lines and count matches将文件中的列表与多行进行比较并计算匹配项
【发布时间】:2023-02-23 01:43:44
【问题描述】:

我在一个文件中有一个包含多个列表的文件,我想比较和计算代码中列表的出现次数。 示例文件:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10
10, 20, 30 ,40 50, 60
25, 35, 45, 55, 65, 75

我的代码有结果列表:

list = [1, 5, 10, 20, 30]

预期输出:

Line 1 = 3 
Line 2 = 3
Line 3 = 0

已经尝试在循环中使用 sum for 但只在第一行工作:

count = sum(f in a for f in list)
print(count)

感谢任何能提供帮助的人。

【问题讨论】:

  • 文件有误,正确的是:1, 2, 3, 4, 5, 6, 7, 8, 9, 1010, 20, 30 ,40 50, 6025, 35, 45, 55, 65, 75
  • 随便抛出一个简单的做法,看看大家有没有问题。

标签: python list


【解决方案1】:

您的逻辑很接近,但您还需要遍历每一行。也不要隐藏像list这样的内置函数

numbers = {1, 5, 10, 20, 30} # Set's are better for lookup

with open("filename.txt") as infile:
    for i, line in enumerate(infile, 1):
        count = sum(int(n) in numbers for n in line.split(", "))
        print(f"Line {i} = {count}")

【讨论】:

    【解决方案2】:

    如果我理解正确的话,这可能就是你要找的?

    注释 - 假设每一行只包含独特的数字。

    
    filename = 'numbers.txt'
    
    L = [1, 5, 10, 20, 30]
    
    counts = []
    
    with open(filename) as fd:
        for line in fd:
            lst = list(map(int, (line.split(','))))
    
            cnt = set(L).intersection(lst)
            
            counts.append(len(cnt))
    
    
    for idx, matches in enumerate(counts, 1):
        print(f' Line {idx}, match = {matches} ')
    
    

    输出:

     Line 1, match = 3 
     Line 2, match = 3 
     Line 3, match = 0 
    
    

    如果每一行都有重复的数字,那么你可以试试这个方法:

    with open(filename) as fd:
        for line in fd:
            lst = list(map(int, (line.split(','))))
    
            #cnt = set(L).intersection(lst)
    
            tot = sum(n in L for n in lst)
            print(f' tot: {tot} ')
            
            counts.append(tot)
    

    【讨论】:

    • 如果同一数字在一行中显示 2x 会怎样?
    • 好问题。由 PO 决定,我的方法只是根据样本输入直接回答。 ;-)
    • 我的方法有问题吗?请分享(无论谁投反对票)。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多