让我们说doc.txt包含
a
b
c
d
Run Code Online (Sandbox Code Playgroud)
我的代码是
f = open('doc.txt')
doc = f.read()
doc = doc.rstrip('\n')
print doc
Run Code Online (Sandbox Code Playgroud)
为什么我得到相同的价值?
我想知道它:
> %timeit sum([int(digit) for digit in str(n)])
100000 loops, best of 3: 1.52 us per loop
> %timeit sum(int(digit) for digit in str(n))
100000 loops, best of 3: 2.04 us per loop
Run Code Online (Sandbox Code Playgroud) 我目前的做法是这样的:
def get_hash(path=PATH, hash_type='md5'):
func = getattr(hashlib, hash_type)()
with open(path, 'rb') as f:
for block in iter(lambda: f.read(1024*func.block_size, b''):
func.update(block)
return func.hexdigest()
Run Code Online (Sandbox Code Playgroud)
在 i5 @ 1.7 GHz 上计算 842MB iso 文件的 md5sum 大约需要 3.5 秒。我尝试了不同的读取文件的方法,但所有这些方法都会产生较慢的结果。也许有更快的解决方案?
编辑:我用 替换了2**16(在 内f.read())1024*func.block_size,因为block_sizehashlib 支持的大多数散列函数的默认值是64(除了 'sha384' 和 'sha512' - 对于它们,默认值block_size是128)。因此,块大小仍然相同(65536 位)。
编辑(2):我做错了什么。它需要 8.4 秒而不是 3.5 秒。:(
编辑(3):当我再次运行该函数时,显然 Windows 正在以 +80% 的速度使用磁盘。真的需要3.5秒。呼。
另一个解决方案(~-0.5 秒,稍微快一点)是使用 os.open():
def get_hash(path=PATH, hash_type='md5'):
func = getattr(hashlib, hash_type)()
f …Run Code Online (Sandbox Code Playgroud) 以此代码为例:
print 2.0 == 2 #---> returns True
print 12 % 5 #---> returns 2
print ((12.0 / 5) - (12 / 5)) * 5 #---> returns 2.0
print ((12.0 / 5) - (12 / 5)) * 5 == 12 % 5 #---> returns False (What the hell happens here?)
Run Code Online (Sandbox Code Playgroud) 例如,如果我这样做,str(bin(66))我得到0b1000010,但如果我这样做str(bin(66)).strip("0b"),我得到100001(注意缺少'0').
我想我是在滥用条形功能.
str(reduce(lambda x, y: x * y, range(1, 11))) -> this returns 10! or '3628800'
Run Code Online (Sandbox Code Playgroud)
在不创建for循环的情况下,如何将此函数作为一位整数列表映射到另一个函数:例如reduce(lambda x, y: x+ y, [3, 6, 2, 8, 8, 0, 0])
澄清:
reduce(lambda x, y: x + y, [str(reduce(lambda x, y: x * y, range(1, 11)))])
如何将内部的所有内容[ ]转换为一位数整数列表,以便第一个函数可以对其进行求值?当然,我需要改变它里面的[ ].
以此代码为例:
if int(str(x)[len(str(x)) - 1]) == 0 or int(str(x)[len(str(x)) - 1]) == 5:
return False
Run Code Online (Sandbox Code Playgroud)
假设我有一个更大的列表or,是否有更简单的方法来做到这一点?
好的,既然我知道使用if x in ( , , , etc),我该如何实现这个:
filter(lambda x: int(str(x)[len(str(x)) - 1]) in (0, 5), range(1000)) 得到它,错误的括号,错误的python程序员.
假设我打开这个文件(wordlist.txt):
...
14613 bore
14614 borg
14615 boric
14616 boris
14621 born
14622 borne
14623 borneo
14624 boron
...
Run Code Online (Sandbox Code Playgroud)
如果变量是例如14623,我如何选择它旁边的单词?
听我说:
我想将一些参数传递给bash中的脚本:python my_python_script.py set_api <api_key>但是我希望将api_key它作为永久变量存储在同一个脚本中.我想知道这是否可能,因为我记得其他选项,比如我可以简单地将变量存储在不同的文件中,并确保我的脚本在其他任何内容之前读取该文件.
什么是最好/最安全的方法?