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

时间:2021-01-17 14:33:25

标签: python for-loop enumerate

我有如下字符串列表:

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

如果想获得基于以下条件的输出:

  • 字符串中的字符是连续的。例如:"a""b""c"、...
  • 列表中的后续元素也是连续的。例如:"abc""bcd"、“cde”、...
  • 如果不满足上述任何条件,则break迭代

对于上面的例子,我需要输出像(以及元素索引):

0 abc
1 bcd
2 cde
4 efc

这是我试过的代码:

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

2 个答案:

答案 0 :(得分:1)

您可以使用 ord() 找到字符的 unicode 代码。在下面的示例中,我使用 zip() 迭代字符串中的连续字符,然后匹配它们的 unicode 代码是连续的。然后我使用 all() 检查字符串的所有 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

答案 1 :(得分:0)

我想出了一个更简单的解决方案

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
相关问题