簡體   English   中英

將值存儲在列表、元組和集合中

[英]Storing values in a List, tuple and sets

問你用戶 4 輸入。 然后,這些必須存儲在列表、元組和集合中。 如果輸入無效,程序將說明 3(列表、元組或集合)中的哪一個不支持用戶輸入的內容並結束程序。 如果成功,程序將打印存儲的數據。 這是我能做的最好的:

num_elements = []
tpl = ()
st = set()

list_length = int(input('Enter the range of the list: '))

try:
    for i in range(list_length):
    item = int(input('Enter the numbers: '))
    var = tpl + (tuple(item))
    num_elements.append(item)
    st.add(item)


print(str(num_elements))
print(tpl)
print(st)

except ValueError:
   print('Please enter a valid key')

我已經修復了您的代碼的一些問題 - 您的 try/except 語法錯誤並且您的元組初始化需要一些更改。 讓我知道這是否適合您的目的。

num_elements = []
tpl = ()
st = set()

list_length = int(input('Enter the range of the list: '))

try:
    for i in range(list_length):
        item = int(input('Enter the numbers: '))
        tpl = tpl + (item,)
        num_elements.append(item)
        st.add(item)
except ValueError:
   print('Please enter a valid key')

print(num_elements)
print(tpl)
print(st)

暫無
暫無

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

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