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

时间:2019-04-11 14:00:28

标签: python list pprint

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

关于stackoverflow的问题很多。我决定使用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]

以此类推。

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

3 个答案:

答案 0 :(得分:2)

您可以打开列表的包装:

[11-Apr-2019 16:05:31 Europe/City] Msg 1

输出

trigger_error()

OR

如果您不保存它们:

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]

答案 1 :(得分:1)

似乎您已经拥有了想要的东西。 如果您执行以下操作:

daily_usage = []
for j in db['Date']:
    max_usage = 0
    min_usage = 100000
    for i in db['Meter Reference']:
        if (i > max_usage):
            max_usage = i
        if (i < min_usage):
            min_usage = i

    daily_usage.append( max_usage - min_usage )

my_lists [0]-> list1 。 。

my_lists [n]-> listn

答案 2 :(得分:0)

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

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