【问题标题】:Nested list manipulation, double forloop needed? [duplicate]嵌套列表操作,需要双 forloop? [复制]
【发布时间】:2015-12-01 04:01:54
【问题描述】:

所以我想改变这个嵌套(列表)让我们称之为 X

[['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']]

这个嵌套(列表)让它Y

[['What if', 'Thing Explainer', 'Alan Turing: The Enigma'], [ 2014,2015,2014], ['Randall Munroe, Randall Munroe, 'Andrew Hodges']]

Y 中的第一项是 X 中第 i 项的第一项。

['What if', 'Thing Explainer', 'Alan Turing: The Enigma']

Y中的第二项是X中第i项的第二项

['Randall Munroe, Randall Munroe, 'Andrew Hodges']

谁能分享一下python的思路和解决方案?

【问题讨论】:

  • map(list, zip(*X))

标签: python nested-loops nested-lists


【解决方案1】:

您将需要在 Python 中使用内置的 zip 函数。

>>> zip(*[['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']])

更多文档位于https://docs.python.org/3/library/functions.html#zip

【讨论】:

  • 您需要将参数解压缩到zip 函数,即zip(*your_list)
  • 是的,我还是想返回一个嵌套循环
【解决方案2】:
map (list, zip(*[['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']]))

这将完全满足您的需求。

【讨论】:

  • 但是如果我按照你的方式操作,我希望返回一个嵌套列表['Thing Explainer', '2015', 'Randall Munroe'], ['Alan Turing: The Enigma', '2014', 'Andrew Hodges']])) print(a)
  • 刚转换成列表对象,谢谢!!!
【解决方案3】:

我不确定您想要/不想使用哪些软件包。但是numpy 可以很容易地做到这一点:

import numpy as np
dat = [['What if?', ' 2014', ' Randall Munroe'], ['Thing Explainer', ' 2015', ' Randall Munroe'], ['Alan Turing: The Enigma', ' 2014', ' Andrew Hodges']]
np.array(dat).T.tolist()
# [['What if?', 'Thing Explainer', 'Alan Turing: The Enigma'],
#  [' 2014', ' 2015', ' 2014'],
#  [' Randall Munroe', ' Randall Munroe', ' Andrew Hodges']]

【讨论】:

  • 抱歉无法导入任何东西:S
猜你喜欢
  • 2019-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多