Python 从包含连续字符字符串和连续后续元素的列表中获取元素

Python 从包含连续字符字符串和连续后续元素的列表中获取元素,python,for-loop,enumerate,Python,For Loop,Enumerate,我有一个字符串列表,如: my_list = ['abc','bcd','cde','def','efc'] 如果希望根据以下条件获得输出: 字符串中的字符是连续的。例如:“a”,“b”,“c” 列表中的后续元素也是连续的。例如:“abc”,“bcd”,“cde” 如果不满足上述任何条件,中断迭代 对于上面的示例,我需要输出如下(以及元素索引): 以下是我尝试的代码: lst = ['abc','bcd','cde','def','efc'] for idx, i in enumerate

我有一个字符串列表,如:

my_list = ['abc','bcd','cde','def','efc']
如果希望根据以下条件获得输出:

  • 字符串中的字符是连续的。例如:
    “a”
    “b”
    “c”
  • 列表中的后续元素也是连续的。例如:
    “abc”
    “bcd”
    ,“cde”
  • 如果不满足上述任何条件,
    中断
    迭代
对于上面的示例,我需要输出如下(以及元素索引):

以下是我尝试的代码:

lst = ['abc','bcd','cde','def','efc']
for idx, i in enumerate(lst):
    if 'c' in i:
        #here should be the other condition
        print(idx,i)
但它只打印这些:

0 abc
1 bcd
2 cde
您可以使用查找字符的unicode代码。在下面的示例中,我使用迭代字符串中的连续字符,然后匹配它们的unicode代码是否连续。然后我使用检查字符串的所有unicode代码是否连续:

my_list = ['abc','bcd','cde','def','efc']

for i, l in enumerate(my_list):
    # check if element is first element in list
    is_first = i == 0

    # check if all the chars are continuous in string
    is_continuous = all(ord(a)+1 == ord(b) for a, b in zip(l, l[1::]))

    # Match the continuation order from previous index element.
    # True, for 1st element
    is_previous_match = is_first or ord(my_list[i-1][0])+1 == ord(l[0])

    if is_continuous and is_previous_match:
        print(i, l)
    else:
        break
将打印:

0 abc
1 bcd
2 cde
3 def

我想出了一个更简单的解决办法

my_list = ['lol','abc','bcd','cd e','def','efc','das da']
index = []
for i,l in enumerate(my_list):
    if 'c' in l:
        index.append(i)
for l in my_list[index[0]:]:
    if 'c' in l:
        print(l)
    else:
        break
abc
bcd
cd e

为什么不
def
?它也在连续模式中,还是我缺少了一些逻辑?明白了,你需要
c
也在场“连续(不间断)索引”是什么意思?如果其中没有“c”,是否要停止?那么也许添加
else:break
会有帮助吗?@YevhenKuzmovych你明白我的意思了,除了
else:break
如果第一个元素不包含
c
t,就不会打印任何东西。你在问题中没有提到这一点。有很多方法可以解释它。因此,您需要提供更多的细节和/或示例。我认为OP的意思是其他东西-如果字符串符合条件并在列表中排成一行,则只打印字符串,而不是字符串中的实际字母。但我可能错了。因为他写的是连续索引,而不是字母。OP的代码中有
if'c'in I
条件,这让我觉得他在找这张支票。他们期望的输出与这种行为相匹配。根据您评论中的逻辑,
def
也应该出现在所需的输出中,对吗?我的意思是,他(可能)正在查找列表中一行中包含“c”的字符串。不是字符串中按字母顺序排成一行的字母,谢谢你的详细回答,但只有当
l
字符串中没有空格时才有效,如果l中的“c”只是在几次匹配后使索引中断的一个例子,这不是我在注释中建议你更简单的要点,使用
takewhile()
。但如果不需要索引,可以使用更简单的选项:
print(*takewhile(lambda x:c'in x,lst),sep='\n')
my_list = ['lol','abc','bcd','cd e','def','efc','das da']
index = []
for i,l in enumerate(my_list):
    if 'c' in l:
        index.append(i)
for l in my_list[index[0]:]:
    if 'c' in l:
        print(l)
    else:
        break
abc
bcd
cd e