How to print every third element from current index in list of elements
我有元素清单
1 2 3 4 5 6 7 8 9 10 11 12 | def printFormat(lst, columns): for i in range(0, len(lst)): print lst[i] for j in range(): #if (i)%3==0: # print lst[i] if __name__ == '__main__': lst = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] columns = 3 printFormat(lst, columns) |
一个一线解决方案是:
1 2 | >>> [lst[i::4] for i in range(4)] [['A', 'E', 'I'], ['B', 'F', 'J'], ['C', 'G'], ['D', 'H']] |
1 2 3 4 5 6 7 | >>> lst ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] >>> num_of_parts=4 >>> newlst=[lst[i::4] for i in range(num_of_parts)] >>> newlst [['A', 'E', 'I'], ['B', 'F', 'J'], ['C', 'G'], ['D', 'H']] >>> |
编辑1:添加一些解释和使用mod运算符的第二种方法
因此,
下面是一些例子,演示了相同的内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> lst [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> lst[1:3] [1, 2] >>> lst[1:] [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> lst[:3] [0, 1, 2] >>> lst[::2] [0, 2, 4, 6, 8] >>> lst[::1] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> lst[1::2] [1, 3, 5, 7, 9] >>> |
号
Mod运算符方法:
1 2 3 4 5 6 7 | >>> lst ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] >>> num_of_parts=4 >>> newlst=[[lst[i] for i in range(len(lst)) if i%4 == j] for j in range(num_of_parts)] >>> newlst [['A', 'E', 'I'], ['B', 'F', 'J'], ['C', 'G'], ['D', 'H']] >>> |
编辑2:使mod operator方法更具可读性,我们得到以下内容:
1 2 3 4 5 6 7 8 9 10 11 12 | >>> lst=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] >>> newlst=[] >>> for j in range(num_of_parts): ... temp=[] ... for i in range(len(lst)): ... if i%4 == j: ... temp.append(lst[i]) ... newlst.append(temp) ... >>> newlst [['A', 'E', 'I'], ['B', 'F', 'J'], ['C', 'G'], ['D', 'H']] >>> |
。