将字符串转换为整数并将其分配给变量

2024-10-03 21:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有一行是“3 2 11”。我想将其拆分为3个“3”、“2”、“11”,然后将它们转换为整数,并将它们分配到各个变量中。我的代码如下:

import sys
for line in sys.stdin:
    print(line, end="")

snailHasNotEscaped = True
days = 0
totalMs = 0

mPerWholeDay = N - M

while snailHasNotEscaped:
   totalMs += mPerWholeDay
   days += 1
   if totalMs >= H:
      snailHasNotEscaped = False

Tags: 代码inimporttrueforstdinsysline
3条回答

我假设您有未知数量的变量,所以我会将它们存储在列表中。
我将使用列表理解来构建新列表:

line = "3 2 11"
lst = line.split()
int_lst = [int(ele) for ele in lst]
print(int_lst)

但是,您可以将其用于:

line = "3 2 11"
lst = line.split()
int_lst = []
for ele in lst:
    int_lst.append(int(ele))
print(int_lst)

您可以使用映射功能:

x, y, z = map(int, input().split())

或者如果您想使用快速I/O

from sys import stdin
x, y, z = map(int, stdin.readline().split())

这是单行线

output = map(int, input.split())

如果输出中没有固定的变量,则

x, y, z = output 

 x, y, z =  map(int, input.split())

相关问题 更多 >