如何枚举组合字符串作为的搜索范围.在循环



我写了一段对我来说有意义的代码,但对python来说不是,因为我是python的新手。

检查我的代码:

checksum_algos = ['md5','sha1']
for filename in ["%smanifest-%s.txt" % (prefix for prefix in ['', 'tag'],  a for a in checksum_algos)]:
  f = os.path.join(self.path, filename)
  if isfile(f):
     yield f

我的目的是在列表中搜索文件名,如:

['manifest-md5.txt','tagmanifest-md5.txt','manifest-sha1.txt','tagmanifest-sha1.txt']

但我有syntax问题来实现它。

谢谢你的帮助

你想太多了。

for filename in ("%smanifest-%s.txt" % (prefix, a)
    for prefix in ['', 'tag'] for a in checksum_algos):

或者您需要itertools.product():

>>> import itertools
>>> [i for i in itertools.product(('', 'tag'), ('sha', 'md5'))]
[('', 'sha'), ('', 'md5'), ('tag', 'sha'), ('tag', 'md5')]

使用新样式字符串格式和itertools:

from itertools import product
["{0}manifest-{1}.txt".format(i,e) for i,e in  product(*(tags,checksum_algos))]

:

['manifest-md5.txt',
 'manifest-sha1.txt',
 'tagmanifest-md5.txt',
 'tagmanifest-sha1.txt']

最新更新