将字符串转换为整数并将它们赋值给变量

3

例如,我有一个字符串 "3 2 11"。我想把它分成三个部分,即 "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

2
你在哪一部分遇到了困难? - quamrana
3
请尝试在Python中查找函数"split"和"int"的用法。 - Ethan
1
这些变量已经存在了吗? - norie
确切地说,输入已被读取,因此最终我希望它们看起来像x=3,y=2和z=11。 - sean
目前该行输出为“3 2 11” - sean
6个回答

1
您可以使用map函数:
x, y, z = map(int, input().split())

或者,如果您想使用快速输入输出(Fast I/O)

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

0
尝试像这样做:

numericString = "3 2 111".split() # Define str and split
listOfNumbers = list() # Create a new list
for s in numericString: # Loop the splitted elements
    listOfNumbers.append(int(s)) # Convert string to integer and append
print(listOfNumbers) # Print the list

0

这是一行代码

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

如果输出中变量的数量是固定的,则
x, y, z = output 

或者

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

0
我假设你有未知数量的变量,所以我会把它们存储在列表中。
我将使用列表推导式来构建新列表:
line = "3 2 11"
lst = line.split()
int_lst = [int(ele) for ele in lst]
print(int_lst)

然而,你可以使用for代替:
line = "3 2 11"
lst = line.split()
int_lst = []
for ele in lst:
    int_lst.append(int(ele))
print(int_lst)

0

@sean。最近怎么样?让我来帮帮你 :)

想象一下你的字符串是

my_string = "3 2 11"

首先,您需要将其拆分为每个数字,如下所示:

my_string.split() 

或者

my_string.split(' ')  #choose your delimiter (ex: '.', ';', ',')

然后Python将返回一个类似于这样的列表

>> [3,2,11]

现在你只需要使用函数int()将变量赋值即可:
a = int(my_string.split()[0]) #For the fist index on the list "3"
b = int(my_string.split()[1]) #For the second index on the list "2" ...
c = int(my_string.split()[2]) #For the second index on the list "11"

或者

a = int(my_string.split(' ')[0]) #For the fist index on the list "3"
b = int(my_string.split(' ')[1]) #For the second index on the list "2" ...
c = int(my_string.split(' ')[2]) #For the second index on the list "11"

0

你好,

阅读了您的描述 - 这是我想尝试的一些内容: 注意:如果我有什么误解,我会很高兴您/其他人指出!

>>> s1="3 2 11"     # the string "3 2 11"
>>> s2=s1.split()   # same string, but split.

>>> s1
'3 2 11'

>>> s2
['3', '2', '11']

>>> ([int(i) for i in s2])  # use type() with a for loop 
[3, 2, 11]                  # to print out every element in the split str `s2`,
                            # as the type int.

# we can also,
# access one element in s2,
# and check what type that element is:
# by (for example) assigning it to a variable "element_1"

>>> element_1 = ([int(i) for i in s2])[0]
>>> element_1
3

# Check what type it is:
>>> type(element_1)
<class 'int'>

## A example of using + and *:

>>> a=([int(i) for i in s2])[0]
>>> b=([int(i) for i in s2])[1]
>>> c=([int(i) for i in s2])[2]

>>> a,b,c
(3, 2, 11)

>>> (a*b)+c
17


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接