【问题标题】:python advance for looppython提前for循环
【发布时间】:2016-03-17 02:04:16
【问题描述】:

我是一只 30 年前使用 BASIC 的老狗。我之前在 python 中使用 for 循环时遇到过这种情况,但我选择这个插图是因为我担心循环:

我想解析一个长字符串,其中包含用逗号分隔的双引号中的单词。我可以忽略双引号,但我希望循环在这里推进。我不觉得这很优雅。我带着不必要的循环行李。我是否应该完全取消循环,在这种情况下,切片是首选方法,是否有一般规则适用于使用循环的问题?

"""
data is the str-type variable
line, despite the name, seems to pull out just one character at a time
(which is not relevant except to confirm my naïveté in python)
"""

for line in data:
    if line.endswith('"'):
        x = True  # doing nothing but advancing the for loop
    elif line.endswith(','):
        #  do something at a comma
    else:
        #  continue the parsing

编辑示例字符串:

"All","the","world","'s","a","stage","And","all","the","men","and","women","merely","players"

【问题讨论】:

  • 你可以使用continue来推进一个循环
  • 循环遍历一个字符串一次拉出一个字符,因为这是定义的行为。我不知道还能怎么说。您可以尝试阅读 official Python tutorial 之类的内容。
  • 是的,你绝对应该重命名line。这对初学者来说非常具有误导性/令人困惑。
  • 谢谢@idjaw;添加了示例输入。我不知道继续命令@cricket_007,谢谢。
  • 你从哪里得到字符串?可能有更好的方法来解析您的数据。

标签: python loops for-loop


【解决方案1】:

我想解析一个长字符串,其中包含用逗号分隔的双引号中的单词

data成为

data = '''"this","is","a","test"'''

那你可以split()逗号

for quote in data.split(','):

我可以忽略双引号

是的,你可以strip()引号

    word = quote.strip('"')

然后打印

    print(word)

大家一起

data = '''"this","is","a","test"'''

for quote in data.split(','):
    word = quote.strip('"')
    print(word)

输出

this
is
a
test

【讨论】:

    【解决方案2】:

    关于循环的一般问题,如果你想逐行解析字符串,你可以这样做:

    for line in data.split('\n'):
        …
    

    for line in data.splitlines():
        …
    

    长字符串,包含用逗号分隔的双引号中的单词。我可以忽略双引号,但我希望循环在这里前进 ...

    但是在多次阅读您的问题之后,您从未说过您实际上想要遍历行。相反,您可能希望以逗号分隔字符串:

    for element in data.split(','):
        …
    

    然后,如果你想删除引号,你可以去掉它们:

        element.strip('"\'')
    

    编辑:

    这里是你的例子,提取每个单词:

    >>> s = '''"All","the","world","'s","a","stage","And","all","the","men","and","women","merely","players"'''
    >>> 
    >>> for element in s.split(','):
    ...     element = element.strip('"')
    ...     print(element)
    ... 
    All
    the
    world
    's
    a
    stage
    And
    all
    the
    men
    and
    women
    merely
    players
    

    HTH

    【讨论】:

    • 问题中哪里说有新行?
    • 好吧,在他的代码中:for line in data 这就是为什么我对这两种情况都有疑问☺
    • 我明白了。我读得太远了行,尽管有名字,似乎一次只提取一个字符
    【解决方案3】:

    由于datastr,for 循环将一次推进一个字符。如果您想将str 拆分为由换行符分隔的行,您可以通过返回行列表的split 方法来实现:

    for line in data.split('\n'):
        # do something with line
    

    【讨论】:

    • 你也可以使用data.splitlines()
    【解决方案4】:

    假设您的 data 是一个包含类似内容的字符串

    "one", "two", "tree", ...
    

    您可以将您的行分成“一”、“二”和“树”块,并去掉这样的引号:

    for element in [x[1:-1] for x in data.split(",")]:
        print element
    

    这利用了所谓的list comprehensions

    【讨论】:

    • 您缺少]。此外,示例输入中没有空格。
    猜你喜欢
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    相关资源
    最近更新 更多