Input comma separated elements (integers), and converts it into list in Python.
输入逗号分隔的元素(整数),并将其转换为Python中的列表。
Example:
例:
Input:
Enter comma separated integers: 10,20,30,40,50
Output:
list: ['10', '20', '30', '40', '50']
List (after converted each element to int)
list (li) : [10, 20, 30, 40, 50]
Logic:
逻辑:
Input a comma - separated string using raw_input() method.
使用raw_input()方法输入逗号分隔的字符串。
Split the elements delimited by comma (,) and assign it to the list, to split string, use string.split() method.
拆分用逗号 ( , )分隔的元素,并将其分配给列表,以使用string.split()方法拆分字符串。
The converted list will contains string elements.
转换后的列表将包含字符串元素。
Convert elements to exact integers:
将元素转换为精确整数:
- for...in loop.for ... in循环遍历列表中的每个数字。
- Convert number (which is in string format) to the integer by using int() method.
- 使用int()方法将数字(字符串格式)转换为整数。
Print the list.
打印列表。
Program:
程序:
# input comma separated elements as string
str = str (raw_input ("Enter comma separated integers: "))
print "Input string: ", str
# conver to the list
list = str.split (",")
print "list: ", list
# convert each element as integers
li = []
for i in list:
li.append(int(i))
# print list as integers
print