【问题标题】:How do i split a list and and turn it into two dimensional list?如何拆分列表并将其转换为二维列表?
【发布时间】:2022-07-30 22:48:20
【问题描述】:

我有一个列表:lst = [1,2,3,4,'-',5,6,7,'-',8,9,10]
遇到'-'字符时需要拆分。并变成这样的二维列表:
[[1,2,3,4],[5,6,7],[8,9,10]]
到目前为止我有这个,它所做的只是去掉“-”字符:

l=[]
for item in lst:
   if item != '-':
      l.append(item)

return l

我正在学习如何编码,所以我很感激帮助

【问题讨论】:

  • 当您所做的只是将项目附加到一个新列表时,您为什么希望它创建一个列表列表,除非它是 '-'
  • 为什么要加减号?引用---“遇到'-'字符时需要拆分。并变成这样的二维列表:[[1,2,3,4],[5,6,7],[8 ,9,10]]"
  • @inquirer 这是一个任务,这就是给定列表的内容
  • @PranavHosangadi 我是说我不明白如何做到这一点,我所包含的代码是我所能想到的,但我知道并不能满足我的需要
  • @abeishere 你能展示你的期望吗?

标签: python python-3.x list split sublist


【解决方案1】:

您可以构建一个仅包含数值的新列表:

new_list = [] #final result
l=[] #current nested list to add
for item in lst:
    if item != '-':
        l.append(item) # not a '-', so add to current nested list
    else: #if item is not not '-', then must be '-'
        new_list.append(l) # nested list is complete, add to new_list
        l = [] # reset nested list
print(new_list)

【讨论】:

    【解决方案2】:
    import numpy as np
    import more_itertools as mit
    
    lst = np.array([1, 2, 3, 4, '-', 5, 6, 7, '-', 8, 9, 10])
    aaa = list(mit.split_at(lst, pred=lambda x: set(x) & {'-'}))
    bbb = [list(map(int, i)) for i in aaa]
    

    输出 bbb

    [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多