converting list of string to list of integer [dupl

2019-02-12 08:13发布

This question already has an answer here:

How do I convert a space separated integer input into a list of integers?

Example input:

list1 = list(input("Enter the unfriendly numbers: "))

Example conversion:

['1', '2', '3', '4', '5']  to  [1, 2, 3, 4, 5]

7条回答
干净又极端
2楼-- · 2019-02-12 09:00

this works:

nums = [int(x) for x in intstringlist]
查看更多
Viruses.
3楼-- · 2019-02-12 09:03

You can try:

x = [int(n) for n in x]
查看更多
做自己的国王
4楼-- · 2019-02-12 09:05

map() is your friend, it applies the function given as first argument to all items in the list.

map(int, yourlist) 

since it maps every iterable, you can even do:

map(int, input("Enter the unfriendly numbers: "))

which (in python3.x) returns a map object, which can be converted to a list. I assume you are on python3, since you used input, not raw_input.

查看更多
Emotional °昔
5楼-- · 2019-02-12 09:05

One way is to use list comprehensions:

intlist = [int(x) for x in stringlist]
查看更多
淡お忘
6楼-- · 2019-02-12 09:08
 l=['1','2','3','4','5']

for i in range(0,len(l)):
    l[i]=int(l[i])
查看更多
戒情不戒烟
7楼-- · 2019-02-12 09:10

Say there is a list of strings named list_of_strings and output is list of integers named list_of_int. map function is a builtin python function which can be used for this operation.

'''Python 2.7'''
list_of_strings = ['11','12','13']
list_of_int = map(int,list_of_strings)
print list_of_int 
查看更多
登录 后发表回答