Python中不规则列的嵌套列表操作

2024-06-01 19:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据集:

Sales = [
["101TGY" , "George" , "Taylor" , 6009 , 5262 , 3745 , 7075 , 1943 , 4432],
["103FCY" , "Fehlix" , "Chayne" , 8717 , 2521 , 5777 , 6189 , 5089 , 6957],
["102SBY" , "Sumren" , "Bergen" , 5012 , 1063 , 7937 , 9560 , 1115 , 5499],
["104SBK" , "Samira" , "Beckle" , 1140 , 9206 , 3898 , 8544 , 5937 , 8705],
["105NBT" , "Nellie" , "Bogart" , 3017 , 3342 , 5939 , 2479 , 3374 , 2297],
["106CGT" , "Cheryl" , "Grouth" , 9620 , 7160 , 5113 , 4803 , 5492 , 2195],
["107DGT" , "Danuta" , "Graunt" , 1583 , 7450 , 1026 , 7463 , 2390 , 6509],
["108JDN" , "Jaiden" , "Deckle" , 4064 , 4978 , 2984 , 3159 , 1464 , 4858],
["109JCK" , "Jimran" , "Caliks" , 6253 , 7962 , 2732 , 7504 , 2771 , 5193],
["110DDN" , "Deynar" , "Derran" , 6305 , 8817 , 5200 , 3647 , 3365 , 1256]]

for i in Sales:
    #do something

如何计算每个人的销售额(整数)

请注意列的数量可能会如何变化。 这意味着代码也应使用此数据集:

Sales = [
["101TGY" , "George" , "Taylor" , "absent", 6009 , 5262 , 3745 , 7075 , 1943 , 4432, 3455],
["103FCY" , "Fehlix" , "Chayne" , 8717 , 2521 , 5777 , 6189 , 5089 , 6957],
["102SBY" , "Sumren" , "Bergen" , 5012 , 1063 , 7937 , 9560 , 1115 , 5499, 345],
["104SBK" , "Samira" , "Beckle" , "absent", 1140 , 9206 , 3898 , 8544 , 5937],
["105NBT" , "Nellie" , "Bogart" , 3017 , 3342 , 5939 , 2479 , 3374 , 2297, 8723],
["106CGT" , "Cheryl" , "Grouth" , 9620 , 7160 , 5113 , 4803 , 5492 , 2195],
["107DGT" , "Danuta" , "Graunt" , 1583 , 7450 , 1026 , 7463 , 2390 , 6509],
["108JDN" , "Jaiden" , "Deckle" , 4064 , 4978 , 2984 , 3159 , 1464 , 4858, 3223],
["109JCK" , "Jimran" , "Caliks" , 6253 , 7962 , 2732 , 7504 , 2771 , 5193],
["110DDN" , "Deynar" , "Derran" , "absent", 6305 , 8817 , 5200 , 3647 , 3365 , 1256]]

我试过做:

for i in Sales:
    total = i[3]+i[4]+i[5]+i[6]+i[8]
    print(total)

这对第一个数据集有效,但对第二个数据集无效,这是一个问题


Tags: 数据salestaylorgeorgeabsentbergencherylbeckle
3条回答

下面的代码应该可以:

total = [0 for i in range(len(Sales))]
count = 0
for i in Sales:
    for j in i:
        if(type(j) == int):
             total[count] += j    
    count+=1
print(total)
sum(i[3] for i in Sales if isinstance(i[3],int) )

38266

您的Sales列表中有嵌套列表。在该子列表中,我们需要添加3元素,并且需要检查它是否是int

Sum  > i[3] ||for i in Sales || if isinstance(i[3],int)

for i in Sales  > For every `sublist` in Sales .
i[3]            > In sublist I'm interested in `3` element. So i[3].
if isinstance(i[3],int)  > I only need the integers.

^{}

Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.

您可以对每个销售行的所有整数值求和

for line in Sales:
    total = sum(i for i in line if isinstance(i, int))
    print(total)

31921
35250
30531
28725
29171
34383
26421
24730
32415
28590

相关问题 更多 >