<分区>
我有一个包含“字符串”类型元素的列表。
li = ['1 ', '2', '3 ', '4', '5 ', '6', '7 ']
我需要更改“int”上每个元素的类型。使用周期是不可取的。
标签 python list python-3.x
<分区>
我有一个包含“字符串”类型元素的列表。
li = ['1 ', '2', '3 ', '4', '5 ', '6', '7 ']
我需要更改“int”上每个元素的类型。使用周期是不可取的。
最佳答案
通过使用 map function ,它返回一个生成器,在这种情况下也返回一个惰性转换(仅当您需要列表中的新元素时才转换):
li = map(int, li)
用你的例子(和 Python 3)
>>> li = ['1 ', '2', '3 ', '4', '5 ', '6', '7 ']
>>> map(int, li)
<map object at 0xffe3ed0c>
>>> list(map(int, li))
[1, 2, 3, 4, 5, 6, 7]
>>> for elem in map(int, li):
... print(elem)
...
1
2
3
4
5
6
7
map
是 some kind of deprecated in the Python community .您可以改用列表理解或生成器:
[int(x) for x in li] # create the full list directly
(int(n) for n in li) # create a generator (note parentheses instead of brackets)
关于python - 如何更改列表中项目的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21736872/