2011-09-14 54 views
6

我願做這樣的事情Python更改整個列表的類型?

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

即充滿INT

任何簡單的方法來做到這一點對嵌套列表全海峽的名單列表,即改變類型[」 1 '],[2' ']] - > INT

+1

你想變異列表或換新的? –

回答

19
map(int, ['1','2','3']) # => [1,2,3] 

這樣:

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

任何簡單的方法來做它的嵌套列表,即改變[['1'],['2']] - > int – bios

+1

的類型,因爲它會'map(lambda sl:map(int,sl) ,[['1'],['2']])=> [[1],[2]]'。 –

+1

'map(foo,[['1'],['2']])' – steabert

0
str_list = ['1', '2', '3'] 
int_list = map(int, str_list) 
print int_list # [1, 2, 3] 
0
def intify(iterable): 
    result = [] 
    for item in iterable: 
     if isinstance(item, list): 
      result.append(intify(item)) 
     else: 
      result.append(int(item)) 
    return result 

作品任意深度嵌套的列表:

>>> l = ["1", "3", ["3", "4", ["5"], "5"],"6"] 
>>> intify(l) 
[1, 3, [3, 4, [5], 5], 6] 
5

列表理解應該這樣做:

a = ['1','2','3'] 
print [int(s) for s in a] # [1, 2, 3]] 

嵌套:

a = [['1', '2'],['3','4','5']] 
print [[int(s) for s in sublist] for sublist in a] # [[1, 2], [3, 4, 5]] 
+0

這不是我想要的,因爲你不能只從int更改爲任何其他你想要的dtype – bios

+0

@bios:我想你會知道如何編寫一個函數來概括這個。 –

+1

@bios是的,你可以。只需將int替換爲一個變量 - 該變量就是您想要的類型。 –

6

這裏是一個相當簡單的遞歸函數轉換任何深度的嵌套列表:

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]]] 
0
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 
+2

請爲此代碼添加一些解釋。 –