我想将 num1 和 num2 转换为一个列表并打印它,关于如何做到这一点的任何输入?
num1 = 12345
num2 = 34266 73628
print num1
print num2
EXPECTED OUTPUT:-
['12345']
['34266','73628']
我想将 num1 和 num2 转换为一个列表并打印它,关于如何做到这一点的任何输入?
num1 = 12345
num2 = 34266 73628
print num1
print num2
EXPECTED OUTPUT:-
['12345']
['34266','73628']
我将假设num1
andnum2
都是字符串(否则您会遇到语法错误)。您可以使用str.split()
:
>>> num1 = '12345'
>>> num2 = '34266 73628'
>>> num1.split()
['12345']
>>> num2.split()
['34266', '73628']
把它们变成字符串,这样你就可以使用拆分,然后把它们变成整数!!
num1 = '12345'
num2 = '34266 73628'
def func(number):
num = number.split()
return [int(i) for i in num]
>>> func(num1)
[12345]
>>>
>>> func(num2)
[34266, 73628]
n1 = '1234 456' #note the single quotes
n2 = '567 879'
def foo(num):
return num.split()
foo(n1)
foo(n2)
和输出:
['1234', '456']
['567', '789']
num1 = '12345'
num2 = '12345 67890'
#Note: Both must be strings
#Option 1(Recommended)
print num1.split()
print num2.split()
#Option 2
import shlex
print shlex.split(num2)
#Option 3
import re
print re.split(' ', num2)
#If the array needs to be of ints:
result1 = [int(item) for item in num1.split()]
result2 = [int(item) for item in num2.split()]
num1 = [12345]
num2 = [34266, 73628]
print num1
print num2