我已经搜索了有关如何执行此操作的相关线程,但我找不到任何内容。
我有一个数组:
x = [a,a,a,b,a,a]
Run Code Online (Sandbox Code Playgroud)
我想将数组的元素复制到新数组中,直到找到“b”。我尝试用循环执行此操作,但收到错误“y 未定义”,我尝试初始化 y 但也不起作用。有任何想法吗?我确信有更好的方法来做到这一点。
for ii in x:
if x[ii].find(num) == 0:
break
else:
y[ii] = x[ii]
Run Code Online (Sandbox Code Playgroud) 我想在 python 中为给定目录创建一个唯一的哈希值。感谢 zmo 提供了下面的代码,为目录中的每个文件生成哈希值,但如何聚合这些代码以生成表示该文件夹的单个哈希值?
import os
import hashlib
def sha1OfFile(filepath):
sha = hashlib.sha1()
with open(filepath, 'rb') as f:
while True:
block = f.read(2**10) # Magic number: one-megabyte blocks.
if not block: break
sha.update(block)
return sha.hexdigest()
for (path, dirs, files) in os.walk('.'):
for file in files:
print('{}: {}'.format(os.path.join(path, file),
sha1OfFile(os.path.join(path, file)))
Run Code Online (Sandbox Code Playgroud) 我试图使用下面的两行从字符串中删除' - '字符,但它仍然返回原始字符串.如果我执行底部两行,它可以工作,sha和sha2都是字符串.有任何想法吗?
sha = hash_dir(filepath) # returns an alpha-numeric string
print sha.join(c for c in sha if c.isalnum())
sha2 = "-7023680626988888157"
print sha2.join(c for c in sha2 if c.isalnum())
Run Code Online (Sandbox Code Playgroud) 我使用下面的命令生成文件列表及其 m5sum。问题是某些文件或文件夹名称中包含空格。我该如何处理这些?
find -type f -name \* | xargs md5sum
Run Code Online (Sandbox Code Playgroud) 我编写了一个实用程序来扫描包含字母字符的所有空格分隔字段的文本文件,它工作得很好但是非常慢,因为我将每行分成单词并扫描每个单词,有更快的方法吗?
谢谢.
这是代码:
#!/bin/python
import argparse
import sys
import time
parser = argparse.ArgumentParser(description='Find all alpha characters in
an input file')
parser.add_argument('file', type=argparse.FileType('r'),
help='filename.txt')
args = parser.parse_args()
def letters(input):
output = []
for character in input:
if character.isalpha():
output = input
return output
def main(argv):
start = time.time()
fname = sys.argv[1]
f = open(fname)
for line in f:
words = line.rstrip().split()
for word in words:
alphaWord = letters(word)
if alphaWord:
print(alphaWord)
f.close()
end = time.time()
elapsed = end - start
print …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种更强大的方法来转换下面的字符串.我想找到3个单词的前3个字母并改变大小写.这些词可以是任何东西,现在我只是为每个小写字母使用字符串替换.
s1 = 'hello.crazy.world.txt'
s1 = s1.replace('h','H')
Run Code Online (Sandbox Code Playgroud)