Python改变整个列表的类型?

时间:2011-09-14 20:18:15

标签: python list

我想做这样的事情

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

即。一个充满str的列表到一个完整的int

列表

为嵌套列表执行此操作的任何简单方法,即更改类型[['1'],['2']] - > INT

7 个答案:

答案 0 :(得分:27)

Python 2:

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

...

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

在Python 3中,map()返回一个地图对象,因此您需要将其转换为列表:

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

...

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

答案 1 :(得分:8)

这是一个非常简单的递归函数,用于转换任何深度的嵌套列表:

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]]]

答案 2 :(得分:7)

列表理解应该这样做:

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]]

答案 3 :(得分:2)

正如对使用map的答案的评论一样。在Python 3中,这不起作用 - 像map(int, ['1','2','3'])这样的东西不会返回[1,2,3]而是一个地图对象。要获取实际列表对象,需要执行list(map(int, ['1','2','3']))

答案 4 :(得分:0)

str_list = ['1', '2', '3']
int_list = map(int, str_list)
print int_list # [1, 2, 3]

答案 5 :(得分: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]

答案 6 :(得分:-1)

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