【问题标题】:Splitting a python list into smaller lists at spaces在空格处将 python 列表拆分为较小的列表
【发布时间】:2018-04-10 10:02:43
【问题描述】:

我有一个由字母和空格组成的列表:

s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j'];

我需要将其拆分为更小的单独列表:

s=[['a','b'],['b','c'],['d','e','f','g','h'],['i','j']]

我是 python 新手。

整个代码:

#To get the longest alphabetical substring from a given string

s = input("Enter any string: ")
alpha_string = []

for i in range(len(s)-1): #if length is 5: 0,1,2,3

if(s[i] <= s[i+1]):
    if i == len(s)-2:
        alpha_string.append(s[i])
        alpha_string.append(s[i+1])
    else:
        alpha_string.append(s[i])

if(s[i] > s[i+1] and s[i-1] <= s[i]):
    alpha_string.append(s[i])
    alpha_string.append(" ")

if(s[i] > s[i+1] and s[i-1] > s[i]):
    alpha_string.append(" ")

print(alpha_string)

#Getting the position of each space in the list
position = []
for j in range(len(alpha_string)):
if alpha_string[j] == " ":
    position.append([j])

print(position)        

#Using the position of each space to create slices into the list
start = 0
final_string = []
for k in range(len(position)):
    final_string.append(alpha_string[start:position[k]])
    temp = position[k]
    start = temp

print(final_string)`

【问题讨论】:

  • 刚接触 StackOverflow 和/或编程并不意味着您可以不费吹灰之力就解决问题。至少展示一次尝试,然后我们可以帮助您解决尝试中的问题。
  • 很抱歉没有显示努力部分。

标签: python list split


【解决方案1】:

尝试如下列表推导

print([list(i) for i in ''.join(s).split(' ') if i != ''])

[['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i' , 'j']]

【讨论】:

  • 这仅适用于单字符串。我们不知道OP的真实数据是否真的都是单字符。
  • 我们也不知道 OP 是否自己努力解决问题。
  • @WillemVanOnsem 和 Aran-Fey,是的。希望他能接受这个并问自己什么是列表理解,然后他去了兔子洞。
  • @JahKnows:我的经验是这将被复制粘贴。我曾经用一些复杂的动态编程方法回答了一个问题。两天后,SO 上出现了另一个问题,正是我从一位想了解该算法的作用的团队成员那里给出的答案。
  • @WillemVanOnsem,我明白了。
【解决方案2】:

这里的生成器将是完美的:

s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j'];

def generator_approach(list_):
    list_s=[]
    for i in list_:
        if i==' ':
            if list_s:
                yield list_s
            list_s=[]
        else:
            list_s.append(i)

    yield list_s

closure=generator_approach(s)
print(list(closure))

输出:

[['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]

【讨论】:

    【解决方案3】:

    或者只是一行,result = [list(item) for item in ''.join(s).split()]

    【讨论】:

      【解决方案4】:

      这是一种实用的方式。

      s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j']
      
      res = list(map(list, ''.join(s).split()))
      
      # [['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]
      

      【讨论】:

        【解决方案5】:
        from itertools import groupby
        
        s = ['a','b',' ',' ','b','c',' ','d','e','f','g','h',' ','i','j']
        
        t = [list(g) for k, g in groupby(s, str.isspace) if not k]
        
        print(t)
        

        输出

        [['a', 'b'], ['b', 'c'], ['d', 'e', 'f', 'g', 'h'], ['i', 'j']]
        

        这并不像许多join()split() 解决方案那样要求字符串是单个字母:

        >>> from itertools import groupby
        >>> 
        >>> s = ['abc','bcd',' ',' ','bcd','cde',' ','def','efg','fgh','ghi','hij',' ','ijk','jkl']
        >>> 
        >>> [list(g) for k, g in groupby(s, str.isspace) if not k]
        [['abc', 'bcd'], ['bcd', 'cde'], ['def', 'efg', 'fgh', 'ghi', 'hij'], ['ijk', 'jkl']]
        >>> 
        

        我永远不能放弃(ab)使用groupby()的机会

        【讨论】:

          猜你喜欢
          • 2018-11-23
          • 1970-01-01
          • 2012-07-12
          • 2016-02-16
          • 2012-11-04
          • 2010-10-19
          • 2012-03-29
          • 2010-12-11
          • 2020-05-05
          相关资源
          最近更新 更多