jcf
jcf

Reputation: 180

Modifying nested lists items inside a for loop

I've been trying to do a couple of simple operations on a nested list but can't seem to find the right way to do it. Here's a sample of the list.

items_q = [['Place1','a=2','b=3','c=4','z=5','d=4'],
           ['Place2','a=2','b=3','c=4','z=5','f=4'],
           ['Place3','a=2','r=3','s=6'],
           ['Place2','a=2','r=3','s=4','z=5'],
           ['Place3','a=2','z=3','d=4']]

I need to extract two things. One is a list of Places and the other is stripping the quantity from each item (letter). I have gotten so far:

places = []

for trx in items_q:
    places.append(trx[0])
    #print(trx[0])
    trx.pop(0)
    for i in trx:
        i = i[:-2]
        #print(i)

This does "almost" all i need. It creates a list of places but does not change the values for each of the letter strings (removing the =x).

The output should be:

items_q = [['a','b','c','z','d'],
           ['a','b','c','z','f'],
           ['a','r','s'],
           ['a','r','s','z'],
           ['a','z','d']]

places = ['Place1', 'Place2', 'Place3', 'Place2', 'Place3']

I realize that the problem must be in the fact that we cannot modify list directly/inplace. Do i need to create a new list and append values? I am stuck.

Thanks!

Upvotes: 1

Views: 52

Answers (3)

kederrac
kederrac

Reputation: 17322

you can use:

places = []
items = []

for p, *i in items_q:
    places.append(p)
    items.append([e[0] for e in i])

print(items)
print(places)

# [['a', 'b', 'c', 'z', 'd'], ['a', 'b', 'c', 'z', 'f'], ['a', 'r', 's'], ['a', 'r', 's', 'z'], ['a', 'z', 'd']]
# ['Place1', 'Place2', 'Place3', 'Place2', 'Place3']

if you want to keep the items in items_q variable:

items_q = items

Upvotes: 1

Olamigoke Philip
Olamigoke Philip

Reputation: 1157

Employ the enumerate function to address each index more accurately:

Comprehensively:

places = []

for trx in items_q:
    places.append(trx[0])
    trx.remove(trx[0]) #Works similarly to Pop but doesn't return removed item in console

    for (index, value) in enumerate(trx):
        trx[i] = value[:-2]

print(items_q)
print(places)

This should return your desired output.

Upvotes: 1

PrinceOfCreation
PrinceOfCreation

Reputation: 397

You need to iterate through as an index, not using the values.

for trx in items_q:
    places.append(trx[0])
    trx.pop(0)
    for i in range(len(trx)): # i is now 0, 1, 2 … len(trx) - 1
        trx[i] = trx[i][:-2] # address the list using index

I would recommend modifying the last line to trx[i] = trx[i].split("=")[0], that will account for having an item name of more than one character (say, 'aa' not 'a')

Upvotes: 2

Related Questions