【问题标题】:How to loop through multiple string variables in a for-loop?如何在for循环中遍历多个字符串变量?
【发布时间】:2019-05-07 05:48:59
【问题描述】:

我有多个存储一些文本数据的字符串变量。我想对所有字符串执行相同的任务集。如何在 Python 中实现这一点?

string_1 = "this is string 1"
string_2 = "this is string 2"
string_3 = "this is string 3"

for words in string_1:
    return the second word 

以上只是一个例子。我想提取每个字符串中的第二个单词。我可以这样做吗:

for words in [string_1, string_2, string_3]:
    return the second word in each string

【问题讨论】:

    标签: python-3.x string for-loop


    【解决方案1】:

    您可以使用列表推导来链接这些字符串中的第二个单词。 split() 通过使用空格将您的句子分解为单词组件。

    lines = [string1, string2, string3]
    
    >>>lines[0].split()
    ['this', 'is', 'string', '1']
    
    >>>[line.split()[1] if len(line.split()) > 1 else None for line in lines]
    ['is', 'is', 'is']
    

    编辑添加条件检查以防止索引失败

    【讨论】:

    • 最好使用line.split(),所以如果有多个空格,它仍然可以工作。另外,listcomp 的问题是,如果句子只有 1 个单词,则在访问第二个元素时会崩溃。
    • @Jean-FrançoisFabre 根据您的建议切换到使用不带字符参数的split,并添加了一个条件语句以防止索引错误。谢谢指出!
    【解决方案2】:

    可以的

    for sentence in [string_1, string_2, string_3]:
       print(sentence.split(' ')[1]) # Get second word and do something with it
    

    假设您在字符串中至少有两个单词并且每个单词由空格分隔,这将起作用。

    【讨论】:

    • 第一次迭代后返回语句退出。这不起作用。
    • 是的。对此感到抱歉。现在做出改变
    猜你喜欢
    • 2016-01-18
    • 2014-11-28
    • 1970-01-01
    • 2023-01-24
    • 2021-01-15
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多