Python - Loop through a 2D List - either append values to the current row or delete it

StackOverflow https://stackoverflow.com/questions/19661201

  •  01-07-2022
  •  | 
  •  

Domanda

I'm attempting to loop through a 2D list, and dependent on factors, either append to the row or remove the entire row

If tempX matches a certain value, tempX and tempY should be appended to the current row in the list. If tempX doesn't match that value, the entire row should be removed from the list.

This is the code so far.

aList = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]

i = 0

for a, b, c, d, e in aList[:]:

    tempC = c
    tempD = D

    tempX = tempC * 2 # These are just a placeholders for another calculation
    tempY = tempD * 2

    if tempX <= 10:
        aList[i].append(tempX)
        aList[i].append(tempY)
    else:
        del aList[i] 

    i += 1

Expected result: aList = [[6, 7, 8, 9, 10, 16, 18], [11, 12, 13, 14, 15, 26, 28]]

Instead this results in

ValueError: too many values to unpack

EDIT

After some research, I've come to this solution.

The key is bList = aList[::-1] ; this splices the list into reverse order, eliminating the situation in the previous example where I was effectively trying to take tyres off a car without a jack.

aList = [[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,30]]
bList = aList[::-1]

i = 0

for a, b, c, d, e in bList:
    tempC = c
    tempD = d

    tempX = tempC * 2
    tempY = tempD * 2

    if tempX >= 50:
        bList[i].append(tempX)
        bList[i].append(tempY)
    else:
        del bList[i]

    i += 1

print bList

Which would be a good solution, apart from the fact that it is skipping every second row. I'm not too sure what is causing it to skip rows.

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

Expected result: bList = [[26, 27, 28, 29, 30, 56, 58]] All the other rows should be deleted

È stato utile?

Soluzione

Without departing too far from your code...

aList = [[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,30]]
bList = []

i = 0

for a, b, c, d, e in aList:
    tempC = c
    tempD = d

    tempX = tempC * 2
    tempY = tempD * 2

    if tempX >= 50:
        bList.append(aList[i]+ [tempX,tempY])
    i += 1

print bList
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top