列表理解;将代码压缩为两行

2024-04-24 16:57:34 发布

您现在位置:Python中文网/ 问答频道 /正文

这个问题的基本轮廓是读取文件,使用关于芬德尔(),查找“[0-9]+”的正则表达式,然后将提取的字符串转换为整数并对整数求和。你知道吗

我已经完成了这个问题,但我想多做一点,把代码压缩成两行。你知道吗

这是我的原始代码:

import re

fh = raw_input("Enter filename: ")
#returns regex_sum_241882.txt as default when nothing is entered
if len(fh)<1 : fh = "regex_sum_241882.txt"
file = open(fh)
sums = list()
#goes through each line in the file
for line in file:
    #finds the numbers in each line and puts them in a list
    nums = re.findall('[0-9]+',line)
    #adds the numbers to an existing list
    for num in nums:
        sums.append(int(num))
#sums the list
print sum(sums)

下面是我当前的压缩代码:

import re
lst = list()
print sum(for num in re.findall('[0-9]+',open("regex_sum_241882.txt").read())): int(num))

它不工作,并给我语法错误:无效语法

有人能给我指出正确的方向吗? 我觉得我也在做同样的事情,但我不确定语法错误是怎么回事。你知道吗


Tags: the代码inretxtforline整数