Python Forum
Converting list elements and sublists from int to str
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting list elements and sublists from int to str
#1
Hello everyone, I'm new to python and currently stuck on a problem,I want to convert a list containing variable data types to strings while maintaining the original structure of the lists, for e.g.

inputlist=['Cities',14,'WACC',(32,'KHI',208.55567),['Stat',14,'RS0']]
Should become

outputlist=['Cities','14','WACC',('32','KHI','208.55567'),['Stat','14','RS0']]
Map doesn't work as it converts the inner tuples and lists to a complete string breaking the original structure.
outputlist=list(map(str,inputlist))
The lists are variable sized with changing internal structures and can be long containing thousands of elements with each element having the possibility of being a tuple or list itself.

Any help would be greatly appreciated.
Reply
#2
hi,

you want to use the right method but not with the right way.

for using map, the first item is a fonction type lambda.

for using lambda, if "x" is your variable for iteration, you can do that :

outputlist= list(map(lambda x: str(x), inputlist))
hope this will be helpful.
Reply
#3
Thanks for the answer but there is still a little problem as you may have observed that the inner tuple and list get converted to a string, I only want their elements to get converted to strings not the whole tuple/list.

Like a recursive function or something.

Any help would be highly appreciated.
Reply
#4
Does "with changing internal structures" mean that list in not always one level deep as in "inputlist"?

If list is only one level deep simple brute-force conversion should suffice. One possibility:

>>> inputlist=['Cities',14,'WACC',(32,'KHI',208.55567),['Stat',14,'RS0']]
>>> outputlist = list()
>>> for el in inputlist: 
...     obj_type = type(el)
...     if isinstance(el, (list, tuple)):           # alternatively: if obj_type in [tuple, list]:
...         outputlist.append([str(x) for x in el])
...         if obj_type == tuple:
...             outputlist[-1] = obj_type(outputlist[-1])
...     else:
...         outputlist.append(str(el))
...
>>> outputlist
['Cities', '14', 'WACC', ('32', 'KHI', '208.55567'), ['Stat', '14', 'RS0']]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
A recursive version, be careful with dictionary keys.
test_data = ['Cities', 14, 'WACC', (32, 'KHI', 208.55567), ['Stat', 14, 'RS0'],
           {'one': 1, 2: [1, 2], (1, 2, 3, 4): ('this', 'that', 10)},
           {1, 2, (3.0, 3.5,), 4}]


def all_strings(data):
    if type(data) == list:
        items = []
        for item in data:
            items.append(all_strings(item))
        return items
    
    elif type(data) == tuple:
        return tuple(all_strings(list(data)))
    
    elif type(data) == dict:
        new_dict = {}
        for key, value in data.items():
            new_dict[all_strings(key)] = all_strings(value)
        return new_dict
    
    elif type(data) == set:
        return set(all_strings(list(data)))

    else:
        return str(data) 


print(all_strings(test_data))
Output:
['Cities', '14', 'WACC', ('32', 'KHI', '208.55567'), ['Stat', '14', 'RS0'], {'one': '1', '2': ['1', '2'], ('1', '2', '3', '4'): ('this', 'that', '10')}, {'4', '2', '1', ('3.0', '3.5')}]
Reply
#6
Thankyou perfringo and yoriz your answers solved my problem, the list will be atmost one level deep in 95% of the cases, as such both answers are perfect.

Thankyou for your help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Why am I getting list elements < 0 ? Mark17 8 1,046 Aug-26-2021, 09:31 AM
Last Post: naughtyCat
  Looping through nested elements and updating the original list Alex_James 3 655 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  Extracting Elements From A Website List knight2000 2 704 Jul-20-2021, 10:38 AM
Last Post: knight2000
  Make Groups with the List Elements quest 2 776 Jul-11-2021, 09:58 AM
Last Post: perfringo
  Converting a list to dictinary tester_V 8 1,000 Jul-02-2021, 09:04 PM
Last Post: tester_V
  I cannot delete and the elements from the list quest 4 1,261 May-11-2021, 12:01 PM
Last Post: perfringo
  List of lists - merge sublists with common elements medatib531 1 1,416 May-09-2021, 07:49 AM
Last Post: Gribouillis
  Take first Elements of sublists quest 2 806 Apr-26-2021, 11:32 AM
Last Post: buran
  Find Common Elements in 2 list quest 4 1,168 Apr-14-2021, 03:57 PM
Last Post: quest
  Sorting Elements via parameters pointing to those elements. rpalmer 3 1,136 Feb-10-2021, 04:53 PM
Last Post: rpalmer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020