使用for循环测试Python中的索引

2024-09-26 18:19:04 发布

您现在位置:Python中文网/ 问答频道 /正文

很简单的问题,虽然我很难解决它。你知道吗

看看代码,我会解释如下:

def printc(some_text):
    split_text = list(some_text)

    for x in split_text:
        if x is '{'
            # this is what i need help with


printc("{CCyan, {RRed, {YYello)

这背后的想法和它仍然是非常早期的代码开发,但我要做的是创建一个迭代器,搜索“split\u text”并找到字符“{”,然后我想测试哪个字符位于它旁边。我该怎么做呢?你知道吗

例如,is搜索split\u文本并找到第一个{我想看看它旁边的字符是不是A、B、C等等。。。你知道吗

有什么想法吗?你知道吗


Tags: 代码textinforifisdefsome
3条回答

如果我需要这样的东西,我通常会成对迭代:

from itertools import tee, izip

def pairwise(iterable):
    """Iterate in pairs

    >>> list(pairwise([0, 1, 2, 3]))
    [(0, 1), (1, 2), (2, 3)]
    >>> tuple(pairwise([])) == tuple(pairwise('x')) == ()
    True
    """
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

用法如下:

for left, right in pairwise(iterable):
    ...
for x, y in zip(some_text, some_text[1:]):
    if x == '{':
        print y

你甚至可以简化它:

chars = [y for (x, y) in zip(some_text, some_text[1:]) if x == '{']

用一个正则表达式就容易多了。你知道吗

import re
re.findall('{(.)', some_text)

输出:

['C', 'R', 'Y']

相关问题 更多 >

    热门问题