簡體   English   中英

如何打印用戶通過輸入選擇的列表?

[英]How do I print a list choosen by the user via input?

我在python程序中定義了兩個列表,我通過input("...")函數獲取用戶輸入。

應該向用戶輸入列表名稱,以便我可以將其打印到控制台,問題是我只能打印列表名稱,而不能打印實際列表本身。

這是我的清單:

aaa = [1,2,3,4,5]
bbb = [6,7,8,9,10]

這是我使用的獲取用戶輸入的代碼:

a = input("Input list name")

這是我用來打印列表的代碼:

print(a)

這是預期的輸出:

[1, 2, 3, 4, 5]

相反,這是我得到的輸出:

aaa

您輸入的內容是str並且在執行print(a)時嘗試打印字符串而不是列表。

您需要了解str和變量名不是同一回事。

aaa'aaa'

您可以在這種情況下使用dict

# store your lists in dict as below
d = {'aaa': [1,2,3,4,5], 'bbb':[6,7,8,9,10]}

a=input('Input list name: ')

# this will handle if user input does not match to any key in dict
try:
    print(d[a])
except:
    print("Please enter correct name for list")

輸出:

[1,2,3,4,5]

嘗試使用locals()函數,如下所示:

aaa = [1, 2, 3, 4, 5]
bbb = [6, 7, 8, 9, 10]
target = input("What list would you like to see? ")
# NOTE: please don't (I REPEAT DON'T) use eval here
#     : it WILL cause security flaws
#     : try to avoid eval as much as possible
if target in locals():
  found = locals()[target]
  # basic type checking if you only want the user to be able to print lists
  if type(found) == list:
    print(found)
  else:
    print("Whoops! You've selected a value that isn't a list!")
else:
  print("Oh no! The list doesn't exist")

這是相同代碼的更簡潔版本:

aaa = [1, 2, 3, 4, 5]
bbb = [6, 7, 8, 9, 10]

target = input("Enter list name: ")

if target in locals():
  found = locals()[target]
  print(found if type(found) == list else "Value is not a list.")
else:
  print("Target list doesn't exist")

注意:第二個答案中的代碼較小,因為我刪除了注釋,使用了較小的消息並添加了三元運算符。

注:查看這個答案這個問題 ,以了解更多關於為什么使用eval是壞的。

祝好運。

暫無
暫無

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

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