繁体   English   中英

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

[英]How to enumerate combined strings as the search range of for..in loop?

因为我是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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM