'Converting all elements to strings in a list of list in Python
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
Solution 1:[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)
Solution 2:[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.
Solution 3:[3]
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']]
Solution 4:[4]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cards |
Solution 2 | SUTerliakov |
Solution 3 | |
Solution 4 | Surya Narayan Jena |