【问题标题】:Create a nested list from numpy array when integer appears [closed]当整数出现时从numpy数组创建一个嵌套列表[关闭]
【发布时间】:2018-01-19 21:06:54
【问题描述】:

我有一个字符串类型的一维数组,如下所示:

["1", "---", "some text", "---", "more text", "---", "2", "---", "even more text", "---", "3", "---", "you guessed it", "---"]

我想要一个具有这种结构的列表:

[
   ["1", "---", "some text", "---", "more text", "---"], 
   ["2", "---", "even more text", "---"], 
   ["3", "---", "you guessed it", "---"]
]

抱歉,如果我的符号有误,我对 Python 中的数据结构还是很陌生。如您所见,每个新的嵌套列表都从数组中接近一个数字开始。

【问题讨论】:

  • 到目前为止你尝试过什么代码?
  • 您需要的输出是无效的数据结构(一组集合)。你到底在追求什么?
  • 你的第一个例子不是一个数组,你的第二个例子不是一个列表,它是一个set 对象,它会抛出一个错误,因为它包含其他集合(不可散列)。
  • 请在 Google 上搜索“Python 中的列表”并使用有效符号更新您的问题
  • 既然问题已经更正并清楚了,请重新打开它。

标签: python arrays list data-structures conditional-statements


【解决方案1】:

假设“数组”是指listtuple

In [22]: data = ("1",
    ...: "---",
    ...: "some text",
    ...: "---",
    ...: "more text",
    ...: "---",
    ...: "2",
    ...: "---",
    ...: "even more text",
    ...: "---",
    ...: "3",
    ...: "---",
    ...: "you guessed it",
    ...: "---")

那么你的逻辑应该很简单:

In [23]: final = []

In [24]: for x in data:
    ...:     if x.isdigit():
    ...:         sub = [x]
    ...:         final.append(sub)
    ...:     else:
    ...:         sub.append(x)
    ...:

In [25]: final
Out[25]:
[['1', '---', 'some text', '---', 'more text', '---'],
 ['2', '---', 'even more text', '---'],
 ['3', '---', 'you guessed it', '---']]

In [26]:

【讨论】:

    【解决方案2】:

    正如其他人所指出的,您已经发布了一个 c 数组样式的期望输出,它在 Python 中转换为一组无效的集合。相反,您可以使用 itertools.groupby 创建嵌套列表:

    import itertools
    s = ["1", "---", "some text", "---", "more text", "---", "2", "---", "even more text", "---", "3", "---", "you guessed it", "---"]
    new_s = [list(b) for a, b in itertools.groupby(s, key=lambda x:x.isdigit())]
    final_data = [new_s[i]+new_s[i+1] for i in range(0, len(new_s), 2)]
    

    输出:

    [
     ['1', '---', 'some text', '---', 'more text', '---'], 
     ['2', '---', 'even more text', '---'], 
     ['3', '---', 'you guessed it', '---']
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-02
      • 2021-07-12
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 2018-11-24
      • 1970-01-01
      相关资源
      最近更新 更多