I would like to do something like this
def foo[x,dtype=long]:
return magic_function_changing_listtype_to_dtype[x]
i.e. a list full of str to a list full of int
any easy way to do it for nested lists, i.e. change the type [['1'],['2']] -> int
asked Sep 14, 2011 at 20:18
biosbios
9573 gold badges11 silver badges19 bronze badges
1
Python 2:
map[int, ['1','2','3']] # => [1,2,3]
...
def foo[l, dtype=long]:
return map[dtype, l]
In Python 3, map[] returns a map object, so you need to convert it to a list:
list[map[int, ['1','2','3']]] # => [1,2,3]
...
def foo[l, dtype=long]:
return list[map[dtype, l]]
RNHTTR
1,9322 gold badges14 silver badges30 bronze badges
answered Sep 14, 2011 at 20:20
Dan D.Dan D.
71.4k13 gold badges98 silver badges118 bronze badges
5
List comprehensions should do it:
a = ['1','2','3']
print [int[s] for s in a] # [1, 2, 3]]
Nested:
a = [['1', '2'],['3','4','5']]
print [[int[s] for s in sublist] for sublist in a] # [[1, 2], [3, 4, 5]]
answered Sep 14, 2011 at 20:31
Steven RumbalskiSteven Rumbalski
43k8 gold badges85 silver badges117 bronze badges
3
Here is a fairly simple recursive function for converting nested lists of any depth:
def nested_change[item, func]:
if isinstance[item, list]:
return [nested_change[x, func] for x in item]
return func[item]
>>> nested_change[[['1'], ['2']], int]
[[1], [2]]
>>> nested_change[[['1'], ['2', ['3', '4']]], int]
[[1], [2, [3, 4]]]
answered Sep 14, 2011 at 20:33
Andrew ClarkAndrew Clark
195k33 gold badges263 silver badges296 bronze badges
str_list = ['1', '2', '3']
int_list = map[int, str_list]
print int_list # [1, 2, 3]
answered Sep 14, 2011 at 20:21
Cat Plus PlusCat Plus Plus
122k26 gold badges195 silver badges222 bronze badges
Just as a comment to the answers here which use map
. In Python 3 this wouldn't work - something like map[int, ['1','2','3']]
will not return [1,2,3]
but a map object. To get the actual list object one needs to do list[map[int, ['1','2','3']]]
answered Apr 13, 2018 at 12:02
tsandotsando
4,1442 gold badges31 silver badges34 bronze badges
def intify[iterable]:
result = []
for item in iterable:
if isinstance[item, list]:
result.append[intify[item]]
else:
result.append[int[item]]
return result
works for arbitrarily deeply nested lists:
>>> l = ["1", "3", ["3", "4", ["5"], "5"],"6"]
>>> intify[l]
[1, 3, [3, 4, [5], 5], 6]
answered Sep 14, 2011 at 20:29
Tim PietzckerTim Pietzcker
318k56 gold badges493 silver badges549 bronze badges
a=input[]#taking input as string. Like this-10 5 7 1[in one line]
a=a.split[]#now splitting at the white space and it becomes ['10','5','7','1']
#split returns a list
for i in range[len[a]]:
a[i]=int[a[i]] #now converting each item of the list from string type
print[a] # to int type and finally print list a
answered Oct 17, 2017 at 13:07
YashYash
1,5031 gold badge17 silver badges22 bronze badges
0