![](/img/trans.png)
[英]How can I take a variable number of files as input for a python script?
[英]How can take input of n number of lists in python?
我們如何在python中獲取n個列表的輸入
例如
2
1 2 3
4 5 6 7
here 2 is specifying number of lists that are going to input
1 2 3 is one list
4 5 6 7 is second list
另一個例子
3
1 2 3
4 5 6 8
2 3 5 7
3表示要輸入3個列表
1 2 3 is list one
4 5 6 8 is list two
2 3 5 7 id list three
我已經完成了這段代碼
n=input()
for i in range(n):
b=map(int,raw_input().split())
我對此感到震驚,我如何才能接受n個列表的輸入,我只能將一個列表放入一個變量中,我想處理不同的變量
我想接受不同的變量
您不能在循環中將輸入分配給“不同”變量,尤其是在您不知道n
會多大的情況下。 相反,您應該將b
的不同值附加到列表列表中,例如bs
。
n = input()
bs = []
for i in range(n):
bs.append(map(int, raw_input().split()))
或使用列表理解:
bs = [map(int, raw_input().split()) for _ in range(n)]
您要從文件還是CLI讀取?
如果您從文件中讀取內容,則可以逐行遍歷其內容,並且只能在特定的行中進行操作。
您可以分割的行輸入將單個數字放入列表中。
nums=[]
with open(infile.txt) as f:
n=0
for i, line in enumerate(f):
if i==1:
n == 1
elif i <= n
nums[i] = line.split()
有幾件事需要解決:
保持簡單,並使用列表而不是地圖。
n = int(input()) rows = [] # will contain the input as a list of integers for i in range(n): row_string = input() row = [int(num) for num in row_string.split()] rows.append(row)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.