![](/img/trans.png)
[英]How to get the n numbers in only one line and put them into a list and according to the list, print characters in python?
[英]How can I ask for n and type the n numbers in only one line
輸入n個數字的通常方法是先詢問n個,然后在不同的行中鍵入n個數字。
n = int(input())
for i in range(n):
x = int(input())
如何要求n並僅在一行中輸入n個數字。
像這樣:
>> 4 1 2 3 4
如何要求n並僅在一行中輸入n個數字。
如果從空格分隔的輸入中可以明顯看出您有多少個整數,則無需詢問n 。
但是,如果輸入字符串格式是不可協商的,則可以通過序列解壓縮來拆分:
n, *num_list = map(int, input().split())
例如,輸入'4 1 2 3 4'
,您將得到以下結果:
print(n, num_list)
4 [1, 2, 3, 4]
要了解以上邏輯:
input().split()
將空格輸入的字符串拆分為一個列表。 map(int, X)
返回應用於X
每個元素的int
的迭代 。 n, *num_list = map(...)
迭代map
對象,並分為第一個和其余對象。 比較習慣的做法是自己計算n
:
num_list = list(map(int, input().split()))
n = len(num_list)
例如,輸入'1 2 3 4'
,您將得到以下結果:
print(n, num_list)
4 [1, 2, 3, 4]
明確輸入數字的唯一目的是提供一個檢查。 這可以通過一個assert
語句來實現:
n, *num_list = map(int, input().split())
assert n == len(num_list), f'Check failed: {n} vs {len(num_list)} provided does not match'
space_separated_numbers = input()
num_list = [int(x) for x in space_separated_numbers.split()]
訣竅是立即將整個輸入作為字符串,然后自己分割。
編輯:如果您只關心獲取第一個數字,則只需獲取第一個值即可。
space_separated_numbers = input()
num = space_separated_numbers.split()[0]
也許您可以嘗試將整個輸入作為字符串處理。 然后將它們轉換為整數。 在這種情況下,您也不需要指定n的值。
>>> x = [int(y) for y in input().split()]
1 2 3 4
>>> x
[1, 2, 3, 4]
然后,您可以通過遍歷列表來使用這些值。 如果需要n的值,則只需獲取列表的長度即可。
>>> n = len(x)
>>> n
4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.