代码之家  ›  专栏  ›  技术社区  ›  rahlf23

Python在到达大写单词时将列表拆分为多个较短的列表

  •  1
  • rahlf23  · 技术社区  · 9 年前

    输入:

    s = ['HARRIS', 'second', 'caught', 'JONES', 'third', 'Smith', 'stole', 'third']
    

    ['HARRIS', 'second', 'caught']
    ['JONES', 'third']
    ['Smith', 'stole', 'third']
    

    最好使用s.index('some regex')来解决这个问题,然后在这些给定的索引处相应地拆分列表吗?

    4 回复  |  直到 9 年前
        1
  •  2
  •   Ajax1234    9 年前

    你可以试试这个:

    s = ['HARRIS', 'second', 'caught', 'JONES', 'third', 'Smith', 'stole', 'third']
    
    indices = [i for i, a in enumerate(s) if a[0].isupper()]
    
    indices.append(len(s))
    
    final_list = [s[indices[i]:indices[i+1]] for i in range(len(indices)-1)]
    

    输出:

    [['HARRIS', 'second', 'caught'], ['JONES', 'third'], ['Smith', 'stole', 'third']]
    

    如果您想要一个任何字母都可以大写的解决方案:

    s = ['HARRIS', 'second', 'caught', 'JONES', 'third', 'Smith', 'stole', 'third']
    
    indices = [i for i, a in enumerate(s) if any(b.isupper() for b in a)]
    
    indices.append(len(s))
    
    final_list = [s[indices[i]:indices[i+1]] for i in range(len(indices)-1)]
    
        2
  •  1
  •   Chris    9 年前

    如果您愿意使用第三方库,您可以使用 iteration_utilities.Iterable 要轻松实现这一点:

    >>> from iteration_utilities import Iterable
    >>> 
    >>> lst = ['HARRIS', 'second', 'caught', 'JONES', 'third', 'Smith', 'stole', 'third']
    >>> Iterable(lst).split(str.isupper, keep_after=True).filter(lambda l: l).as_list()
    [['HARRIS', 'second', 'caught'], ['JONES', 'third', 'Smith', 'stole', 'third']]
    
        3
  •  0
  •   delta    9 年前

    一种直接的方法是枚举列表,当创建资本时,我们开始一个新的列表,否则追加。

    s = ['HARRIS', 'second', 'caught', 'JONES', 'third', 'Smith', 'stole', 'third', 'H']
    
    def split_by(lst, p):
        lsts = []
        for x in lst:
            if p(x):
                lsts.append([x])
            else:
                lsts[-1].append(x)
        return lsts
    
    print(split_by(s, str.isupper))
    
        4
  •  0
  •   ZRTSIM    9 年前
    str.istitle("Abc") #True
    str.istitle("ABC") #False
    str.istitle("ABc") #False
    
    str.isupper("Abc") #False
    str.isupper("ABC") #True
    str.isupper("ABc") #False
    

    Checking if first letter of string is in uppercase

    a = "Abc"
    print(str.isupper(a[0]))
    

    或

    a = "Abc"
    print(a[0].isupper())