我试图使用split在同一行上获取3个整数输入,但是会引发错误
int()参数必须是字符串,类似字节的对象或数字,而不是 “列表”
这是我的代码
n,a,k = int(input().split())
答案 0 :(得分:3)
请尝试
n,a,k = map(int, input().split())
int
只能接收一个字符串。
答案 1 :(得分:1)
您可能想像这样使用map
:
n,a,k = map(int, input().split())
作为split
函数将返回list
而不是str
。
map
将int
函数应用于str
的每个元素(list
)。
答案 2 :(得分:1)
由于其他人提供了git status
解决方案,因此以下是使用简单列表理解的解决方案:
map
它比n,a,k = [int(i) for i in input().split()]
有优势吗?并非如此,但有些人更喜欢这种方法。
答案 3 :(得分:0)
OR:
import ast
n,a,k = ast.literal_eval(','.join(input().split()))
print(n,a,k,sep='\n')
示例输出:
1 2 3
1
2
3
答案 4 :(得分:0)
即使您输入的字母包含至少3个数字或更多的字母,您也可以使用以下过程方法来完成相同的操作。
如果您还要输入少于3个数字的字符串,则函数将对其进行处理,并为对应的变量返回0。示例包含在最底部。请看看。
import re
def get_inputs(n=3):
inp = input('Enter a sentence with at least 3 numbers included: ').strip()
arr = re.sub(r'[^0-9]+', ' ', inp).strip().split()
if len(arr) < n:
for i in range(n):
try:
arr[i]
except IndexError as e:
arr.append(0)
n, a, k, *rest = list(map(int, arr))
return (n, a, k, rest)
# Start
if __name__ == "__main__":
# Get 3 numbers
out1 = get_inputs()
n, a, k, rest = out1
print('n =', n)
print('a =', a)
print('k =', k)
print('rest = ', rest)
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python get_numbers.py
Enter a sentence with at least 3 numbers included: Hello, I like 65, 45 and 90 ok.
n = 65
a = 45
k = 90
rest = []
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python get_numbers.py
Enter a sentence with at least 3 numbers included: 12, 23 and 67 are nice but 34 and 23 also.
n = 12
a = 23
k = 67
rest = [34, 23]
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python get_numbers.py
Enter a sentence with at least 3 numbers included: 12 34 56
n = 12
a = 34
k = 56
rest = []
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python get_numbers.py
Enter a sentence with at least 3 numbers included: 45 12 34 21 12 hello 99
n = 45
a = 12
k = 34
rest = [21, 12, 99]
rishi@Rishidev MINGW64 /c/Rishikesh67/Projects/Working/hygull.github.io/codes/python3.6 (master)
$ python 1.py
Enter a sentence with at least 3 numbers included: Now 67 is best for me.
n = 67
a = 0
k = 0
rest = []