Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使每个n';一个列表中的元素在其自己的列表中?_Python_Python 3.x - Fatal编程技术网

Python 如何使每个n';一个列表中的元素在其自己的列表中?

Python 如何使每个n';一个列表中的元素在其自己的列表中?,python,python-3.x,Python,Python 3.x,例如,我有一个如下设置的列表: values = ['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma', ' 1979', ' 2014', ' 2015', ' 2014', ' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges'] 我想把每4个元素(或我定义的任何元素)放入它们自己的列表中

例如,我有一个如下设置的列表:

values = ['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma', ' 1979', ' 2014', ' 2015', ' 2014', ' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges']
我想把每4个元素(或我定义的任何元素)放入它们自己的列表中,这样就可以了

values = [['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma'], [' 1979', ' 2014', ' 2015', ' 2014'], [' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges']]
我的尝试是创建一个for循环,遍历所有元素,并将它们转换为如下列表:

values = ['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma', ' 1979', ' 2014', ' 2015', ' 2014', ' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges']
for x in range(0,len(values),1):
    values[x:x+4] = [values[x:x+4]]
然而,当我试着运行这个时,我得到了

[['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma'], [' 1979', ' 2014', ' 2015', ' 2014'], [' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges'], [], [], [], [], [], [], [], [], []]
所以我的代码就是我想要它做的,但是它也留下了一些空的[],这是我不想要的。我怎样才能解决这个问题

编辑:::NVM,我修复了它

是的

它成功了


感谢那些花时间回答这个问题的人,即使最后我不需要帮助,我还是感谢你的时间。

你应该用长度除以4或n

for x in range(0,len(values)/4):
     values[x:x+4] = [values[x:x+4]]

对于范围内的x(0,len(值),4):
?这是我得到的结果,但是你在LOL后5秒就回答了,谢谢你提供了正确的解决方案
for x in range(0,len(values)/4):
     values[x:x+4] = [values[x:x+4]]