3

I have a list of lists:

lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]

I want to iterate over each element and perform some string operations on them for example:

replace("(", "")

I tried iterating over the list using:

for l1 in lst1:
   for i in l1:
       lst2.append(list(map(str.replace("(", ""), l1)))

I wanted the out result to be the same as original list of lists but without the parenthesis. Also, I am looking for a method in editing lists of lists and not really a specific solution to this question.

Thank you,

3 Answers 3

8

Edit:

Yes, you should use normal for-loops if you want to:

  1. Preform multiple operations on each item contained in each sub-list.

  2. Keep both the main list as well as the sub-lists as the same objects.

Below is a simple demonstration of how to do this:

main = [["(a)", "(b)", "(c)"], ["(d)", "(e)", "(f)", "(g)"]]

print id(main)
print id(main[0])
print id(main[1])
print

for sub in main:
    for index,item in enumerate(sub):

        ### Preform operations ###
        item = item.replace("(", "")
        item = item.replace(")", "")
        item *= 2

        sub[index] = item  # Reassign the item

print main
print
print id(main)
print id(main[0])
print id(main[1])

Output:

25321880
25321600
25276288

[['aa', 'bb', 'cc'], ['dd', 'ee', 'ff', 'gg']]

25321880
25321600
25276288

Use a nested list comprehension:

>>> lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]
>>> id(lst1)
35863808
>>> lst1[:] = [[y.replace("(", "") for y in x] for x in lst1]
>>> lst1
[['a)', 'b)', 'c)'], ['d)', 'e)', 'f)', 'g)']]
>>> id(lst1)
35863808
>>>

The [:] will keep the list object the same.

Sign up to request clarification or add additional context in comments.

11 Comments

yes, list comprehensions are useful for this if you just want to make a one liner. Although you are technically still using a nested for loop, my soln. is the correct answer based on how @user3263488 was thinking
@Ol'Reliable - Well, I'll add a solution that uses normal for-loops. The nested list comprehension one though should work fine in most cases.
I like this approach. Now a real problem. I want to take a different list. one with XYZ coordinates like this: [[(12.22, 12.122, 0.000)], [(1232.11, 123.1231, 0.000)]]. Is there a way to nest a few operations? I want to strip it of parenthesis and commas then multiply each coordinate by a number and put it back together like it was. Any ideas?
this is probably why i wanted to use a for loop since i can perform multiple operations in a row. right?
what do you mean by "strip it of ... commas"? You still need commas for the elements
|
0

I just did what you did, i used the fact that each element of a list can be assigned a new (or updated) value:

>>> lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]
>>> for x in range(len(lst1)):
        for y in range(len(lst1[x])):
            lst1[x][y] = lst1[x][y].replace("(", "")
>>> lst1
[['a)', 'b)', 'c)'], ['d)', 'e)', 'f)', 'g)']]

EDIT

This is how you do it with the "real problem" that you mentioned in the comment:

a = [[(12.22, 12.122, 0.000)], [(1232.11, 123.1231, 0.000)]]
some_num = 10
for x in range(len(a)):
    b = list(a[x][0])
    for y in range(len(b)):
        b[y] *= some_num
    a[x] = tuple(b)
print(a)

OUTPUT:

[(122.2, 121.22, 0.0), (12321.099999999999, 1231.231, 0.0)]

^ All elements have been multiplied by a number and the original format is kept

This is how it works:

So you have the initial list 'a' that has two sublists each with only ONE element (the tuple that contains the x,y,z coordinates). I go through list 'a' and make the tuples a list and set them equal to 'b' (so the fourth line has a value of [12.22, 12.122, 0.000] the first time around (and the next tuple (as a list) the next time around).

Then I go through each of the elements in 'b' (the tuple converted into a list) and multiply each element in that tuple by a number with the use of the increment operator (+=, -=, /=, *=). Once this loop is done, I set that same position in the master list 'a' equal to the tuple of the previously converted tuple. < If this doesn't make sense, what I'm saying is that the initial tuples are converted into lists (then operated on), and then converter back to tuples (since you want it to end up with the same format as before).

Hope this helps!

9 Comments

you could use for L in lst1: for i, x in enumerate(L): L[i] = x.replace("(", "") instead of range()
yes, you are correct, there are many ways to do this problem, i just answered it in his way of thinking. Personally, i would've done it the way @user3263488 did it
On my previous comment, I meant the user @iCodez
@Ol'Reliable this is working very well. Can you break it down step by step for me? I know this is asking a lot but i want to understand what is happening in every part of the code not just copy your solution. Thank you so much!
range(0, len(lst1)) is redundant, range(len(lst1)) is enough
|
0
>>> lst1 = [["(a)", "(b)", "(c)"],["(d)", "(e)", "(f)", "(g)"]]
>>> [[j.strip('()') for j in i] for i in lst1]
[['a', 'b', 'c'], ['d', 'e', 'f', 'g']]
>>> [[j.lstrip('(') for j in i] for i in lst1]
[['a)', 'b)', 'c)'], ['d)', 'e)', 'f)', 'g)']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.