【问题标题】:Get elements from list containing string of continuous chars and continuous subsequent element从包含连续字符字符串和连续后续元素的列表中获取元素
【发布时间】:2021-01-17 14:33:25
【问题描述】:

我有如下字符串列表:

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

【问题讨论】:

  • 为什么不def?它也是连续模式还是我错过了一些逻辑?
  • 知道了,您还需要c 出席
  • “连续(不间断)索引”是什么意思?如果里面没有'c',你想停下来吗?所以也许添加else: break 有帮助?
  • @YevhenKuzmovych 你明白我的意思,除了else: break 如果第一个元素不包含c t 不会打印任何东西。
  • 您在问题中没有提到这一点。有很多方法可以解释它。因此,您需要提供更多详细信息和/或示例。

标签: python for-loop enumerate


【解决方案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

【讨论】:

  • 我认为 OP 意味着别的东西——如果它们遵循条件并在列表中连续出现,则只打印字符串,而不是字符串中的实际字母。但我可能错了。
  • 因为他写的是连续索引,而不是字母。
  • OP 在代码中有if 'c' in i 条件,这让我觉得他正在寻找这个检查。并且他们想要的输出与该行为相匹配。根据您评论中的逻辑,def 也应该出现在所需的输出中,对吧?
  • 我的意思是,他(s)正在(可能)在列表中寻找带有“c”的字符串。不是字符串本身按字母顺序排列的字母
  • 感谢详细的答案,但仅当l 字符串中没有空格时才有效,if 'c' in l 部分只是在几次匹配后使索引中断的示例,它不是点本身
【解决方案2】:

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

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

【讨论】:

  • 我建议你在 cmets 中使用更简单的 takewhile()。但是如果你不需要索引,你可以使用更简单的选项:print(*takewhile(lambda x: 'c' in x, lst), sep='\n')
猜你喜欢
  • 2023-03-13
  • 2021-12-05
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
  • 2019-02-23
相关资源
最近更新 更多