如何遍历字符串列表以在条件中使用它们?

时间:2011-10-31 14:38:25

标签: python

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()

5 个答案:

答案 0 :(得分:4)

由于你的所有字符串都是相同的长度,你可以这样做:

if line[:3] in days:
    break

如果这是一个太多的假设:

if any(line.startswith(day) for day in days):
    break

另一个提示(假设您使用的是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

并且您不必考虑手动关闭文件,即使发生异常也是如此。

如果你仍然使用Python 2.4或更低版本(为什么??)只需构建自己的any()函数:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

答案 1 :(得分:4)

查看help(str.startswith),您可以看到该方法接受要搜索的字符串元组,因此您可以一步完成所有操作:

>>> 'Mon is the first day'.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'))
True

这是一个在旧版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

答案 2 :(得分:3)

if line.startswith(tuple(days)):

来自文档:

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.

最后一行是你问题的答案。

答案 3 :(得分:1)

试试这样:

if line[:3] in days:
    # True
    pass

答案 4 :(得分:-1)

#Hackish, but works
if min([line.find(x) for x in days]) == 0: