2

我想将 num1 和 num2 转换为一个列表并打印它,关于如何做到这一点的任何输入?

num1 = 12345
num2 = 34266 73628


print num1
print num2

EXPECTED OUTPUT:-

['12345']
['34266','73628']
4

5 回答 5

3

我将假设num1andnum2都是字符串(否则您会遇到语法错误)。您可以使用str.split()

>>> num1 = '12345'
>>> num2 = '34266 73628'
>>> num1.split()
['12345']
>>> num2.split()
['34266', '73628']
于 2013-06-18T02:58:52.753 回答
0

把它们变成字符串,这样你就可以使用拆分,然后把它们变成整数!!

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]
于 2013-06-18T03:01:32.540 回答
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']
于 2013-06-18T03:04:54.703 回答
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()]
于 2013-06-18T03:29:54.527 回答
-2
num1 = [12345]
num2 = [34266, 73628]


print num1
print num2
于 2013-06-18T02:58:55.473 回答