我想将num1和num2转换为列表并打印出来,有关如何进行此操作的任何输入?
num1 = 12345
num2 = 34266 73628
print num1
print num2
EXPECTED OUTPUT:-
['12345']
['34266','73628']
答案 0 :(得分:3)
我将假设num1
和num2
都是字符串(否则您会出现语法错误)。您可以使用str.split()
:
>>> num1 = '12345'
>>> num2 = '34266 73628'
>>> num1.split()
['12345']
>>> num2.split()
['34266', '73628']
答案 1 :(得分:0)
让它们成为字符串,这样你就可以使用split,然后将它们变成整数!!
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]
答案 2 :(得分:0)
n1 = '1234 456' #note the single quotes
n2 = '567 879'
def foo(num):
return num.split()
foo(n1)
foo(n2)
输出:
['1234', '456']
['567', '789']
答案 3 :(得分:0)
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()]
答案 4 :(得分:-2)
num1 = [12345]
num2 = [34266, 73628]
print num1
print num2