gpt4 book ai didi

python - 将平面列表转换为python中的列表列表

转载 作者:IT老高 更新时间:2023-10-28 20:43:17 25 4
gpt4 key购买 nike

人们可能想做与扁平化列表相反的事情,like here : 我想知道如何将平面列表转换为列表列表。

在 numpy 中,您可以执行以下操作:

>>> a=numpy.arange(9)
>>> a.reshape(3,3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])

我想知道你是如何做到相反的,我通常的解决方案是:

>>> Mylist
['a', 'b', 'c', 'd', 'e', 'f']
>>> newList = []
for i in range(0,len(Mylist),2):
... newList.append(Mylist[i], Mylist[i+1])
>>> newList
[['a', 'b'], ['c', 'd'], ['e', 'f']]

有没有更“pythonic”的方式来做到这一点?

最佳答案

>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd'), ('e', 'f')]

正如@Lattyware 所指出的,这只有在每次返回元组时 zip 函数的每个参数中都有足够的项目时才有效。如果其中一个参数的项目少于其他参数,则项目被切断,例如。

>>> l = ['a', 'b', 'c', 'd', 'e', 'f','g']
>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd'), ('e', 'f')]

如果是这种情况,那么最好使用@Sven Marnach 的解决方案

How does zip(*[iter(s)]*n) work

关于python - 将平面列表转换为python中的列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10124751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com