在删除嵌套列表的列时,列分配索引超出范围。

2024-06-08 11:28:50 发布

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

我有一个嵌套列表,每个列表中都有一些东西。它看起来像这样:

itemsOnShelf=[[3,5,6,8],
              [2,3,7,3],
              [4,2,2,3]]

每一列都属于一个项目,例如列1/位置0为1。 在我的程序中,我有一个函数为每列添加所有项并将它们保存到变量中,例如potatoes=9

我还有一个保存这些变量的列表,它看起来像这样:

food=[potatoes, tomatoes, apples, peaches]

我还有一个函数,如果列中的项之和小于某个特定的数字,它将删除该列,例如11。你知道吗

minimumNumberAllowed=11
smallestNumber=[]

def throwAway(thing,pos):
   for item in smallestNumber:
    if item==thing:
        for shelf in itemsOnShelf:
            for veg in shelf:
                del shelf[pos]
                print(itemsOnShelf)

接下来我有一段代码是这样的:

for item in food:
       if item < minimumNumberAllowed: 
              smallestNumber.append(min(food))
              print(smallestNumber)
              for item in smallestNumber:
               throwAway(potatoes,0)
               throwAway(tomatoes,1)
               throwAway(apples,2)
               throwAway(peaches,3)

这个想法是,如果一列(项目)太少,它将被删除。我的问题是,一旦删除了一列,就会出现“list assignment index out of range”错误,因为现在列越来越少,因此第3列将不存在。这是一个阻碍我在我的编码前进的问题。我尝试使用while len(itemsOnShelf)<=3或其他数字,但它所做的是它在列被删除之前停止,所以我收到一个不变的列表。如何修复此索引超出范围错误,以便记录删除,索引自行更正?你知道吗

编辑:我不能手动删除列,因为主列表中的项目数可以更改,所以我并不总是控制需要删除的列。你知道吗


Tags: 项目函数in列表forfooditemtomatoes
3条回答

你已经发现了问题-

now there are fewer columns and therefore column number 3 will not exist

显然,列索引不再相同。删除列0(“potates”)后,列0现在将替换为“tomatoes”等。你知道吗

有几种方法可以解决这个问题,但它们取决于您以后如何使用这个矩阵。您可以将“potations”列保留在那里,并将所有值设置为0,或设置为-1之类的“null”值,这表示它已被“删除”,但仍保持矩阵不变。如果这样做,那么所有的索引值仍然有效。你知道吗

如果您必须实际删除它,那么您必须调整所有索引,以说明列0现在是“西红柿”等事实

有了^{}列表,您就可以处理数据并按其键名调用它们。现在在删除一个值之后,您不再知道任何位置中存在什么。你知道吗

您的现有数据:

itemsOnShelf = [[3,5,6,8],
               [2,3,7,3],
               [4,2,2,3]]
food=['potatoes', 'tomatoes', 'apples', 'peaches']

可以修改为目录列表:

m = [dict(zip(food, i)) for i in itemsOnShelf]
print(m)

[{'tomatoes': 5, 'peaches': 8, 'apples': 6, 'potatoes': 3},
 {'tomatoes': 3, 'peaches': 3, 'apples': 7, 'potatoes': 2},
 {'tomatoes': 2, 'peaches': 3, 'apples': 2, 'potatoes': 4}]

每种食物你都可以得到:

total = {k: sum(i[k] for i in m) for k in m[0]}
print(total)

{'tomatoes': 10, 'potatoes': 9, 'apples': 15, 'peaches': 14}

当总和小于允许的最小值时,您可以删除所有dict的项:

for i in m:
    for k in total:
        if total[k]<11:
            i.pop(k)
print(m)

[{'peaches': 8, 'apples': 6},
 {'peaches': 3, 'apples': 7}, 
 {'peaches': 3, 'apples': 2}]

为什么不用字典?您甚至可以从现有数组和项目名称中形成字典:

item_dict = {k: [l[j] for l in itemsOnShelf] for j, k in enumerate(food)}

或者使用numpy(使阵列切片更容易):

import numpy as np  # for convenience
itemsOnShelf = np.array(itemsOnShelf)  # lets us use numpy slicing -not necessary, just easier
item_dict = {k: itemsOnShelf[:, j] for j, k in enumerate(food)}

您可以使用以下操作删除项目:

def throw_away(key):
    if sum(item_dict[key]) >= max_allowed:
        item_dict.pop(key)  # remove the item from the dictionary

最后一部分:

max_allowed = # some threshold
for key in food:
    throw_away(key)

相关问题 更多 >