编写更短,可读,更pythonic的代码

dyl*_*yln 5 python

我正在尝试制作更短,更pythonic,可读的python.我为Project Euler的问题8提供了这个有效的解决方案(找到1000位数字中5个连续数字的最大乘积).

写这个脚本更pythonic版本的建议?

numstring = ''
for line in open('8.txt'):
    numstring += line.rstrip()

nums = [int(x) for x in numstring]

best=0
for i in range(len(nums)-4):
    subset = nums[i:i+5]
    product=1
    for x in subset:
        product *= x
    if product>best:
        best=product
        bestsubset=subset

print best
print bestsubset
Run Code Online (Sandbox Code Playgroud)

例如:下面的代码片段必须有一个单行代码.我确定这里有一个过去的主题,但我不确定如何描述我在下面做的事情.

numstring = ''
for line in open('8.txt'):
    numstring += line.rstrip()
Run Code Online (Sandbox Code Playgroud)

有什么建议?多谢你们!

ste*_*eha 1

这是我的解决方案。我尝试编写我知道如何编写的最“Pythonic”的代码。

with open('8.txt') as f:
    numstring = f.read().replace('\n', '')

nums = [int(x) for x in numstring]

def sub_lists(lst, length):
    for i in range(len(lst) - (length - 1)):
        yield lst[i:i+length]

def prod(lst):
    p = 1
    for x in lst:
        p *= x
    return p

best = max(prod(lst) for lst in sub_lists(nums, 5))
print(best)
Run Code Online (Sandbox Code Playgroud)

可以说,这是最理想的情况之一,reduce所以也许prod()应该是:

# from functools import reduce   # uncomment this line for Python 3.x
from operator import mul
def prod(lst):
    return reduce(mul, lst, 1)
Run Code Online (Sandbox Code Playgroud)

我不喜欢尝试写一行行,因为有理由需要多行。我真的很喜欢这个with语句,并且我习惯将它用于所有 I/O。对于这个小问题,你可以只做一行,如果你使用 PyPy 或其他东西,当你的小程序完成执行并退出时,文件将被关闭。但我喜欢使用两行代码,with所以我写了这个。

我喜欢@Steven Rumbalski 的一句台词:

nums = [int(c) for c in open('8.txt').read() if c.isdigit()]
Run Code Online (Sandbox Code Playgroud)

我可能会这样写:

with open("8.txt") as f:
    nums = [int(ch) for ch in f.read() if ch.isdigit()]
Run Code Online (Sandbox Code Playgroud)

同样,对于这种短程序,当程序退出时,您的文件将被关闭,因此您实际上不需要担心确保文件被关闭;但我喜欢养成使用的习惯with