簡體   English   中英

如何使用帶輸入的“for”循環創建列表列表

[英]How do you create a list of lists using a 'for' loop with input(s)

我正在嘗試使用輸入 function 和“for”循環創建列表/記錄,但我似乎無法獲得多個列表來填充。 理想情況下,我希望能夠定義要創建的子列表的數量,然后輸入每個列表的信息,直到創建指定列表的總數。

def new_row(n):
    for i in n:
        y = []
        month = input('Enter the month: ')
        city = input('Enter the city: ')
        numCoups = input('Enter the number of coupons accepted: ')
        numAds = input('Enter the number of advertisments ran: ')
        l = [month, city, numCoups, numAds]
        y.append(l)

new_row(input('How many entries do you wish to input'))
def new_row(n):
    y=[] #outside the loop
    for i in range(n)#range function:
        month = input('Enter the month: ')
        city = input('Enter the city: ')
        numCoups = input('Enter the number of coupons accepted: ')
        numAds = input('Enter the number of advertisments ran: ')
        l = [month, city, numCoups, numAds]
        y.append(l)
    new_row(int(input('How many entries do you wish to input'))) #int function 

您應該在循環外聲明列表並且您應該將輸入轉換為 integer,因為默認情況下它是一個字符串,您應該在 for 循環中使用 range func

您需要在 for 循環之外創建初始列表,並且需要將輸入轉換為 integer 並使用 range(n) 而不是 n:

def new_row(n):
    y = []
    for i in range(int(n)):
        month = input('Enter the month: ')
        city = input('Enter the city: ')
        numCoups = input('Enter the number of coupons accepted: ')
        numAds = input('Enter the number of advertisments ran: ')
        l = [month, city, numCoups, numAds]
        y.append(l)
    return y

new_row(input('How many entries do you wish to input'))
def new_row(n):
    y = [] # outside the loop, otherwise it keeps on getting reset
    for i in range(n): # or [for i in range(int(n)):], if n is a string
        month = input('Enter the month: ')
        city = input('Enter the city: ')
        numCoups = input('Enter the number of coupons accepted: ')
        numAds = input('Enter the number of advertisments ran: ')
        l = [month, city, numCoups, numAds]
        y.append(l)

new_row(int(input('How many entries do you wish to input')))
        #you need to do int(input()) because input normally returns a string, but you want a number

如果 n 是一個數字,你應該將 n 更改為 range(n) 它不清楚 n,你還必須通過將它留在循環之外來讓 y 增長,因為它總是會被丟棄,最后你必須返回 y 的值,因為如果你不這樣做'這樣做你也是在丟棄它,如果你想重用它,也許你可以將它作為參數傳遞。 例如:

def new_row(n, y=[]):
    for i in range(n):
        month = input('Enter the month: ')
        city = input('Enter the city: ')
        numCoups = input('Enter the number of coupons accepted: ')
        numAds = input('Enter the number of advertisments ran: ')
        l = [month, city, numCoups, numAds]
        y.append(l)
    return y

result_rows=new_row(input('How many entries do you wish to input'))

暫無
暫無

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

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