Will Python change the type of the whole list?

I would like to do something like this

def foo(x,dtype=long): return magic_function_changing_listtype_to_dtype(x) 

i.e. list, full str, to list, full int

any easy way to do this for nested lists i.e. change type [['1'], ['2']] → int

+6
source share
6 answers
 map(int, ['1','2','3']) # => [1,2,3] 

So:

 def foo(l, dtype=long): return map(dtype, l) 
+19
source

Here is a fairly simple recursive function to convert 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]]] 
+7
source

The explanations in the lists should do this:

 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]] 
+6
source
 str_list = ['1', '2', '3'] int_list = map(int, str_list) print int_list # [1, 2, 3] 
0
source
 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 arbitrary deeply nested lists:

 >>> l = ["1", "3", ["3", "4", ["5"], "5"],"6"] >>> intify(l) [1, 3, [3, 4, [5], 5], 6] 
0
source
 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 
0
source

Source: https://habr.com/ru/post/897346/


All Articles