Python – 整数字符串到整数列表
给定一个由负数和正数组成的整数字符串,转换为整数列表。
Input : test_str = ‘4 5 -3 2 -100 -2’
Output : [4, 5, -3, 2, -100, -2]
Explanation : Negative and positive string numbers converted to integers list.
Input : test_str = ‘-4 -5 -3 2 -100 -2’
Output : [-4, -5, -3, 2, -100, -2]
Explanation : Negative and positive string numbers converted to integers list.
方法 #1:使用列表理解 + int() + split()
在此,我们使用 split() 分割整数,而 int() 用于整数转换。使用列表推导插入到列表中的元素
Python3
# Python3 code to demonstrate working of
# Integers String to Integer List
# Using list comprehension + int() + split()
import string
# initializing string
test_str = '4 5 -3 2 -100 -2 -4 9'
# printing original string
print("The original string is : " + str(test_str))
# int() converts to required integers
res = [int(ele) for ele in test_str.split()]
# printing result
print("Converted Integers : " + str(res))
Python3
# Python3 code to demonstrate working of
# Integers String to Integer List
# Using map() + int()
import string
# initializing string
test_str = '4 5 -3 2 -100 -2 -4 9'
# printing original string
print("The original string is : " + str(test_str))
# int() converts to required integers
# map() extends logic of int to each split
res = list(map(int, test_str.split()))
# printing result
print("Converted Integers : " + str(res))
输出
The original string is : 4 5 -3 2 -100 -2 -4 9
Converted Integers : [4, 5, -3, 2, -100, -2, -4, 9]
方法 #2:使用 map() + int()
在此,整数转换逻辑的扩展任务是使用 map() 完成的。
Python3
# Python3 code to demonstrate working of
# Integers String to Integer List
# Using map() + int()
import string
# initializing string
test_str = '4 5 -3 2 -100 -2 -4 9'
# printing original string
print("The original string is : " + str(test_str))
# int() converts to required integers
# map() extends logic of int to each split
res = list(map(int, test_str.split()))
# printing result
print("Converted Integers : " + str(res))
输出
The original string is : 4 5 -3 2 -100 -2 -4 9
Converted Integers : [4, 5, -3, 2, -100, -2, -4, 9]