简体   繁体   English

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

[英]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.

相关问题 循环遍历字符串列表并使用正则表达式条件编辑它们(python) - looping through a list of strings and edit them with a regex condition (python) 如何在Python中遍历字符串列表 - How to loop through a list of strings in Python 有没有办法遍历列表并将它们单独用作索引? - Is there a way to loop through a list and use them individually as an index? Python:循环浏览两个列表,如果满足条件则添加到它们中,但是每次循环浏览列表中的每个元素 - Python: Loop through two lists, adding to them if condition is met, but looping through every element of the list everytime 如何循环结果并将它们存储在列表中,以便我可以在我的Django模板中使用它们 - How do I loop through results and store them in a list so I can use them in my Django template 如何遍历值列表并将它们复制并粘贴到 PyAutoGui 中? - How to loop through a list of values and copy and paste them in PyAutoGui? 通过列表循环引用它们时如何修改 dataframe - how to modify dataframe when referring them through a list loop 如何遍历城市列表以计算它们之间的距离 - How to loop through list of cities to calculate distances between them Python 如何遍历包含变量的字符串列表? - Python How do you loop through a list of strings that contain variables? 如何根据用户输入循环遍历字符串列表 - How to loop through a list of strings based on user input
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM