如何使用 pprint 将列表的一部分保存在新列表中?

How to save parts of a list in new lists using pprint?

我尝试使用 Python 将列表分成等份。因为我想重用输出,所以我想从零件中创建新列表。

Whosebug 上有很多问题。我决定使用 pprint。

l = list(range(100))
n = 15
def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]
import pprint
pprint.pprint(list(chunks(list(range(0, 100)), 10)))

实际结果如下:

[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 ]

等等

我希望输出像

list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

等等。

-> 如何自动创建此类列表?我不想手动为列表名称编号。

看来你已经得到了你想要的。 如果你这样做:

my_lists = list(chunks(list(range(0, 100)), 10))

my_lists[0] -> 列表 1 . . .

my_lists[n] -> listn

您可以解压列表:

l = list(range(100))
n = 15
def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]
import pprint

res = (list(chunks(list(range(0, 100)), 10)))
lstA, lstB, lstC, lstD, lstE, lstF, lstG, lstH, lstI, lstJ = [*res]

pprint.pprint(lstA)
pprint.pprint(lstB)

输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

如果你不保存它们:

print(res[0])
print(res[1])

输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

如果您只是在寻找一种打印块的方法,您可以使用具有跨度范围的简单循环:

l = list(range(100))
n = 10
for i in range(0,len(l),n): 
    print(f"list{1+i//n} = {l[i:i+n]}")

# output:
list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
list3 = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
list4 = [30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
list5 = [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
list6 = [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
list7 = [60, 61, 62, 63, 64, 65, 66, 67, 68, 69]
list8 = [70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
list9 = [80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
list10 = [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

如果您需要实际变量(list1、list2、...),您可以在循环中使用 exec() 但这将很难在程序的其余部分使用(与列表的列表相反) ):

for i in range(0,len(l),n):
    exec(f"list{1+i//n} = l[i:i+n]")

...

listOfLists = [ l[i:i+n] for i in range(0,len(l),n) ]

...

listOfLists[0] is same as list1
listOfLists[1] is same as list2 
...
listOfLists[K-1] is same as listK