簡體   English   中英

接受用戶輸入並將其附加到元組? Python

[英]Taking user input and appending it to a tuple? Python

所以基本上我正在嘗試創建一個包含預算的電影列表,但我不知道如何獲取輸入並將其放入元組

movie_list = ()
while True:
    title = print("Enter movie: ")
    budget = print("Enter budget: ")
    movie_list.append(title, budget)
    user = input("Would you like to add more movies? (y) or (n)").upper
    if user == 'N':
        break
    if user != 'N' and 'Y':
        print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)

元組不能很好地處理追加。 但是列表可以:


movie_list = []   # make a list, not a tuple
while True:
    title = print("Enter movie: ")
    budget = print("Enter budget: ")
    movie_list.append( (title, budget) ) # append a 2-tuple to your list, rather than calling `append` with two arguments
    user = input("Would you like to add more movies? (y) or (n)").upper
    if user == 'N':
        break
    if user != 'N' and 'Y':
        print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)

由於元素的不可變屬性,您不能將元素添加到元組中。 您不能 append 用於元組。

元組在 Python 中是不可變的。 您不能添加到元組。

元組不是像列表或數組那樣的數據結構。 它旨在將一組值保存在一起,而不是同一類值的列表。

我想我得到了你想要的,我猜你想要一個元組列表。 在這種情況下,只需將第一行變量更改為列表。

我改進了您的代碼,以便您的邏輯有效:

movie_list = []  # movie_list is a list
while True:
    title = input("Enter movie: ")  # Use input() to get user input
    budget = input("Enter budget: ")
    movie_list.append((title, budget))  # Append a tuple to the list

    # movie_list is now a list of tuples

    # Check if the user wants to add another movie
    more = None
    # Loop until the user enters a valid response
    while True:
        more = input("Add another? (Y/N): ").upper()
        if more in ("Y", "N"):
            break
        print("Invalid input")

    # If the user doesn't want to add another movie, break out of the loop
    if more == "N":
        break

    # Else, continue the loop


print(movie_list)

除了編碼,要編寫任何程序,首先應該知道程序的目的及其結果。 如果您可以在此處顯示您想要的確切 output,那么會更好,而不是創建或附加的列表。 據我了解您的要求,您應該使用字典概念 go 以便您可以將數據成對存儲,例如電影及其預算。

{“電影”:預算}

在輸入預算時,請確定是否要將輸入值限制為 integer 或者您希望將其作為字符串允許,例如以千萬為單位。 希望這會幫助你。

暫無
暫無

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

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