0

I have a list of list which has both integers and strings inside it as their values. Now I want to convert all the values to string.

My list of list looks like : (say final_rule)

[[3, '*', 1, 4, 1], [1, 2, '*', 2, 1], ['*', '*', 3, 4, 1], [2, 2, '*', 2, 1]]

And I am trying to produce an output as:

[['3', '*', '1', '4', '1'], ['1', '2', '*', '2', '1'], ['*', '*', '3', '4', '1'], ['2', '2', '*', '2', '1']]

I am trying the below code:

new_list=[]
for list_ in final_rule:
    #print("list_:",list_)
    [str(i) for i in list_]
    new_list.append(i)
return new_list

4 Answers 4

2

You are close! Comprehension is fine, but it does not modify list in place, it creates a new one. So you need to append new list:

def stringify(final_rule):
    new_list=[]
    for list_ in final_rule:
        #print("list_:",list_)
        strings = [str(i) for i in list_]
        new_list.append(strings)
    return new_list

But you can achieve the same with a single comprehension:

def stringify(final_value):
    return [[str(i) for i in inner] for inner in final_value]

Alternatively, inner list may be constructed with list(map(str, inner)), but I'm not sure what will be faster.

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

Comments

2
int_list = [[3, '*', 1, 4, 1], [1, 2, '*', 2, 1], ['*', '*', 3, 4, 1], [2, 2, '*', 2, 1]]

# you can use nested loop like following.
str_list = [[str(i) for i in j] for j in int_list]

output

[['3', '*', '1', '4', '1'],
 ['1', '2', '*', '2', '1'],
 ['*', '*', '3', '4', '1'],
 ['2', '2', '*', '2', '1']]

4 Comments

Can you explain a little?
Dev that is just another way of writing nested loops in a single line.
What is data in the code?
@Dev edited, that was int_list. my bad.
1
lst = [[3, '*', 1, 4, 1], [1, 2, '*', 2, 1], ['*', '*', 3, 4, 1], [2, 2, '*', 2, 1]]

list(list(map(str, terms)) for terms in lst)

Comments

1

Here is one way of doing it using the map() and List Comprehension.

a = [[3, '*', 1, 4, 1], [1, 2, '*', 2, 1], ['*', '*', 3, 4, 1], [2, 2, '*', 2, 1]]
result = [list(map(str,x)) for x in a]

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.