Python列表理解与多个变量

Imm*_*lxR 3 python list-comprehension list

我试图从另一个列表中的索引获取具有特定输出的列表,例如:

L = [(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10,...etc), (...etc)]
multiple_index = [entry[0, 3, 4] for entry in L] 
#----> I know this specific code is wrong
Run Code Online (Sandbox Code Playgroud)

如果上面的代码可以输出我会喜欢它:

[(0, 3, 4), (6, 9, 10), (...etc)]
Run Code Online (Sandbox Code Playgroud)

我希望主列表中每个索引的各个子索引按照所示进行分组,如果可能的话,我想知道我可以使用哪些代码来正确地将其关闭,谢谢.

编辑:另外,我怎么能格式化它显示为干净的行,我使用.writelines和一个单独的输出行将它们输出到文本文件,再次感谢!

Mar*_*ers 8

用途operator.itemgetter():

from operator import itemgetter

multiple_index = map(itemgetter(0, 3, 4), L)
Run Code Online (Sandbox Code Playgroud)

或者在列表理解中:

multiple_index = [itemgetter(0, 3, 4)(i) for i in L]
Run Code Online (Sandbox Code Playgroud)

  • @ImmortalxR:因为我不小心输入了一个逗号,这是一个完整的停止.你也有整数输入,所以你需要先映射到`str`:''\n'.join([','.join(map(str,i))for for multiple_index])` (2认同)