简体   繁体   English

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

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

I worked out a code that make sense to me but not python since I'm new to python. 因为我是python的新手,所以我制定了对我来说有意义的代码,但对python没有意义。

Check my code here: 在这里检查我的代码:

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

My intention is to search filename in a list like : 我的意图是在类似以下列表中搜索文件名:

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

but I got syntax problem to implement it. 但是我遇到了syntax问题来实现它。

Thanks for any help. 谢谢你的帮助。

You're overthinking it. 您想得太多了。

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

Or you need itertools.product() : 或者您需要itertools.product()

>>> import itertools

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

Using new style string formatting and itertools : 使用新样式的字符串格式和itertools

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

out: 出:

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