Python 3.x 如何使用循环按节拆分多行列表
如果一个_列表是一个包含多行整数的列表,那么假设使用三个循环将该列表的拆分版本打印为三部分:第一行加上后面两行,中间一行加上前后两行,最后一行加上前面两行Python 3.x 如何使用循环按节拆分多行列表,python-3.x,Python 3.x,如果一个_列表是一个包含多行整数的列表,那么假设使用三个循环将该列表的拆分版本打印为三部分:第一行加上后面两行,中间一行加上前后两行,最后一行加上前面两行 Print entire list a_list if its length is less than or equal to 3 times section_size (an int). Otherwise, print the first section_size elements of a_list, followed by an e
Print entire list a_list if its length is less than or equal to
3 times section_size (an int).
Otherwise, print the first
section_size elements of a_list, followed by an ellipsis ("...")
followed by the middle section_size elements, followed by another
ellipsis, followed by the final section_size elements.
Note: This function assumes its parameters' values are valid, and
does no exception handling.
这应该起作用:
def contract(lst, size=3):
if len(lst) <= size * 3:
return lst
mid = (len(lst) - 1) // 2
mid_size = (size - 1) // 2
new_lst = lst[:size]
new_lst += ["..."] + lst[mid-mid_size:mid+mid_size+1]
new_lst += ["..."] + lst[-size:]
return new_lst
lst = [[0, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[1, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[2, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[3, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[4, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[5, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[6, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[7, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[8, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[9, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[10, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[11, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[12, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[13, 0, 1, 2, 3, 4, 5, 6, 7, 8],
[14, 0, 1, 2, 3, 4, 5, 6, 7, 8]]
for row in contract(lst, 3):
print(row)
[0, 0, 1, 2, 3, 4, 5, 6, 7, 8]
[1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
[2, 0, 1, 2, 3, 4, 5, 6, 7, 8]
...
[6, 0, 1, 2, 3, 4, 5, 6, 7, 8]
[7, 0, 1, 2, 3, 4, 5, 6, 7, 8]
[8, 0, 1, 2, 3, 4, 5, 6, 7, 8]
...
[12, 0, 1, 2, 3, 4, 5, 6, 7, 8]
[13, 0, 1, 2, 3, 4, 5, 6, 7, 8]
[14, 0, 1, 2, 3, 4, 5, 6, 7, 8]