簡體   English   中英

如何創建一個字典,允許用戶輸入中的多個鍵並打印出組合在一個字符串中的鍵值?

[英]How to create a dictionary that allows multiple keys in a user input and print out key values combined in one string?

我堅持使用 python 字典並感謝您的幫助,因為我在互聯網上沒有找到類似問題的任何示例。

我正在嘗試創建一個允許

  1. 在用戶輸入字段中輸入多個鍵
  2. 然后打印出在一個字符串中輸入的鍵的所有值。

例如,如果用戶輸入“country1, country2, country3”,程序會打印出“'location1', 'location2', 'location3'。

在下面的代碼中,它只允許一個國家和打印出一個位置。 我嘗試了使用列表、字典、元組的不同方法 - 無法弄清楚。

country_dict = {
'country1': 'location1',
'country2': 'location2',
'country3': 'location3',
}

country = input("Enter country: ")
if country.lower() == 'country1':
    country_dict['country1']
if country.lower() == 'country2':
    country_dict['country2']
if country.lower() == 'country3':
    country_dict['country3']

print (country_dict[country])

您可以解析輸入,然后查找位置:

country_dict = {
'country1': 'location1',
'country2': 'location2',
'country3': 'location3',
}

country = input("Enter country: ")
countries = country.split()
locations = ''
for key in country_dict.keys():
    if key in countries:
        locations += f'{country_dict[key]} '

print(locations)

示例:輸入: country1 country2輸出: location1 location2

#declare country_dict
country_dict = {
'country1': 'location1',
'country2': 'location2',
'country3': 'location3',
}
#take input country(s)
country = input("Enter country: ")
out=[]
for i in country.split(","): #Change split string based on your requirement
    out.append(country_dict[i])

print (",".join(out)) #change join string based on your requirement

試試下面的注釋代碼:

countries = input("Enter country: ").split(',') # split the input based on ,
result = []
for c in countries: # iterate over the input countries
    result.append(country_dict.get(c.strip().lower(), '')) # get value from the dict, empty string if key is not found

print(', '.join(result)) # join the result using ', ' 

暫無
暫無

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

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