簡體   English   中英

在Python的單行中接受不同的輸入

[英]Taking different Inputs in single line of Python

我正在嘗試從Python的一行中獲取輸入,但是它不起作用。

錯誤:

Traceback (most recent call last):
File "solution.py", line 4, in <module>
a = int(input())
ValueError: invalid literal for int() with base 10: '1 4'

碼:

q = int(input())
lis = []
for i in range(q) :
  a = int(input())
  print(a)
  if(a==1) :
    b = int(input())
    lis.append(b)
  else :
    print("Do Nothing")

在此代碼中,給定整數即q。

我必須接受兩個輸入,如果第一個整數為1,則必須將第二個輸入添加到數組中。

表格輸入:

5
1 4
1 9

如果第一行的輸入為1,則必須在列表中添加4。 我無法在第1行中接受輸入,因為只有1會同時接受1和4。

分割輸入,然后轉換為int,然后執行任何操作

a = input().split()
a=[int(x) for x in a]
#a is now a list of ints
....#do other stuff

這是最基本的方法

string = input()  # Read Input as string
print(string)

str_array = string.split(" ")  # Split the string
print(str_array)

int_arr = [int(i) for i in str_array]  # Parse the individual strings to int
print(int_arr)

產量

1 56 9 87 7
['1', '56', '9', '87', '7']
[1, 56, 9, 87, 7]

如果您真的想要最Python化的方式

int_arr = [int(i) for i in input().split(" ")]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM