[英]How to loop through a list of strings to use them in a condition?
source = open("file1")
out = open("file2", "w")
days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
for line in source:
out.write(line)
if line.startswith('HERE IS WHERE I WOULD LIKE THE DAYS TO BE LOOPED'):
break
out.close()
Since all your strings are the same length, you could do this: 由于您的所有字符串都是相同的长度,您可以这样做:
if line[:3] in days:
break
If that's too much of an assumption: 如果这是一个太多的假设:
if any(line.startswith(day) for day in days):
break
Another tip (assuming you're on Python 2.7 or 3.2: 另一个提示(假设您使用的是Python 2.7或3.2:
with open("file1") as source, open("file2", "w") as out:
for line in source:
out.write(line)
if any(line.startswith(day) for day in days):
break
and you don't have to think about closing your files manually, even if an exception occurs. 而且即使发生异常,您也不必考虑手动关闭文件。
And if you're still on Python 2.4 or lower (why??) just build your own any()
function: 如果你仍然使用Python 2.4或更低版本(为什么??)只需构建自己的any()
函数:
def any(iterable):
for element in iterable:
if element:
return True
return False
Looking at help(str.startswith)
, you can see that the method accepts a tuple of strings to search for, so you can do it all in one step: 查看help(str.startswith)
,您可以看到该方法接受要搜索的字符串元组,因此您可以一步完成所有操作:
>>> 'Mon is the first day'.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'))
True
Here is a variant that runs on older versions of Python: 以下是在旧版本的Python上运行的变体:
>>> import re
>>> days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
>>> pattern = '|'.join(days)
>>> if re.match(pattern, 'Tue is the first day'):
print 'Found'
Found
if line.startswith(tuple(days)):
from the documentation: 从文件:
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
The last line is the answer to your question. 最后一行是你问题的答案。
Try it like this: 试试这样:
if line[:3] in days:
# True
pass
#Hackish, but works
if min([line.find(x) for x in days]) == 0:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.