在下文中,我尝试使用 map 函数将第一个列表转换为整数列表,我该如何实现这一点
T1 = ['13', '17', '18', '21', '32']
print T1
T3=[map(int, x) for x in T1]
print T3
[[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]]
Expected is:
T3=[13,17,18,21,32]
在下文中,我尝试使用 map 函数将第一个列表转换为整数列表,我该如何实现这一点
T1 = ['13', '17', '18', '21', '32']
print T1
T3=[map(int, x) for x in T1]
print T3
[[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]]
Expected is:
T3=[13,17,18,21,32]
>>> T1 = ['13', '17', '18', '21', '32']
>>> T3 = list(map(int, T1))
>>> T3
[13, 17, 18, 21, 32]
这与以下内容相同:
>>> T3 = [int(x) for x in T1]
>>> T3
[13, 17, 18, 21, 32]
所以你正在做的是
>>> T3 = [[int(letter) for letter in x] for x in T1]
>>> T3
[[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]]
希望这能消除混乱。
>>> T1 = ['13', '17', '18', '21', '32']
>>> print [int(x) for x in T1]
[13, 17, 18, 21, 32]
您的列表理解中不需要地图。Map 创建另一个列表,因此您最终得到一个列表列表。
警告:如果字符串被授予为数字,这将起作用,否则将引发异常。
你可以这样做
>>>T1 = ['13', '17', '18', '21', '32']
>>>list(map(int,T1))
1.首先,map函数是map(func,iterable) 2.看这个例子:
T1=['13','17','18','21','32']
T3=[map(int, x) for x in T1]
print T3
[[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]]
when choose x out,such as '13',is a sequence,so map(int,'13') return [1,3],so the iterable in map(func,iterable) is string.
3.看这个例子:
T1 = ['13', '17', '18', '21', '32']
>>>list(map(int,T1))
map 函数中的可迭代对象是 list.so 'int' 适用于 '13' 作为 13