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

2024-10-03 02:39:46 发布

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

因为我是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问题。你知道吗

谢谢你的帮助。你知道吗


Tags: path代码intxtforprefixfilenamesha1
3条回答

你想得太多了。你知道吗

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

或者你需要^{}

>>> 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']

相关问题 更多 >