例如说我有一个像这样设置的列表:
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个元素(或ni定义的任何元素)放入自己的列表中,这样就可以
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,我修复了它。
我做了
for x in range(0,int(len(values)/4),1):
values[x:x+4] = [values[x:x+4]]
它奏效了
感谢那些花了一些时间来回答这个问题的人,尽管最终我不需要帮助,我感谢您的宝贵时间。
您应将长度除以4或n
for x in range(0,len(values)/4):
values[x:x+4] = [values[x:x+4]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句