首页 > 解决方案 > 当我满足特定条件时,如何在 i 的任一侧组合 Python 列表元素

问题描述

Stack Overflow 上已经有一个类似的问题,请参阅链接,但我在引用 i 之前的项目时遇到问题。我正在使用字符串列表,并且只需要在某个字符串以特定字符开头时组合列表中的相邻字符串,因为该字符串错误地划分了相邻字符串。例如:

list = ["a","b","<s16","c","d"]

在这种情况下,我想组合与以开头的字符串相邻的任意两个元素"<s16"(以开头,因为每次出现都包含不同的数字)。所以正确的列表应该是这样的:list = ["a","bc","d"]

我尝试了几种方法,反复出现的问题是:

  1. i.startswith不适用于整数对象(当我尝试使用range(len(list))例如字符串索引时)
  2. 尝试在之前引用该对象i(例如list.pop(i-1))导致不受支持的操作数类型的类型错误,我猜是因为它认为我正在尝试从字符串中减去 1,而不是在以<s16>

我已经尝试使用re.matchre.findall解决第一个问题,但它似乎并没有准确地找到正确的列表项。 if any(re.match('<s16') for i in list):

提前感谢您的帮助,我也提前为我的无知道歉,我是新手。

标签: pythonlistconditional-statementsneighbours

解决方案


最好是使用re模块

import re

mylist = ["<s1", "a","b","<s16", "<s18", "c", "d", "e", "f", "<s16", "g", "h", "i", "j", "<s135"]

# So you will catch strings which starts with "<s" followed by some digits
# and after zero or more entries of any caracter.
r = "^<s\d+.*"
i = 0
while i < len(mylist):
    item = mylist[i]
    
    # If you are at the start of the list just pop the first item
    if (i == 0) and re.search(r, item):
        mylist.pop(i)
    
    # If you are at the end of the list just pop the last item
    elif (i == len(mylist) - 1) and re.search(r, item):
        mylist.pop(i)
    
    # If you have found a wrong item inside the list
    # continue until you delete all consecutive entries
    elif re.search(r, item):
        mylist.pop(i)
        item = mylist[i]
        while re.search(r, item):
            mylist.pop(i)
            item = mylist[i]
        
        mylist[i-1] += mylist[i]
        mylist.pop(i)
    
    else:
        i += 1

print(mylist)

# ['a', 'bc', 'd', 'e', 'fg', 'h', 'i', 'j']

PS:您可以使用更多正则表达式添加更多选项来捕捉不同的情况


推荐阅读