簡體   English   中英

如何打印“和”字。 列表中的字典

[英]How to print 'and' word. Dictionary inside a list

所以我在列表中有一本字典。 並在該字典中列出。

travel_log =[
{
    "country": "Russia",
    "visits": 2,
    "cities": ["Moscow", "Saint Petersburg"]
},
]

我想打印出來:

你去過莫斯科和聖彼得堡。

如何?

這會起作用:

print(f"You have been to {travel_log[0]['cities'][0]} and {travel_log[0]['cities'][0]}")

你可以試試這個方法

print("You've been to" + " and ".join(travel_log[0]['cities']))

請試試這個:

for country in travel_log:
cities = ""
cities_size = len(country["cities"]) - 1
for idx, city in enumerate(country["cities"]):
    if idx > 0:
        if cities_size == idx:
            cities += " AND "
        else:
            cities += ", "

    cities += city
    
print("You've been to "+cities+" at "+country["country"])

有便利的inflect package。 您需要使用pip install inflect

import inflect

travel_log =[
{
    "country": "Russia",
    "visits": 2,
    "cities": ["Moscow", "Saint Petersburg"]
},
]

p = inflect.engine()
for journey in travel_log:
    print(f"You have been to {p.join(journey['cities'])}") 

output

You have been to Moscow and Saint Petersburg

如果超過 2 個元素,它將是,例如:

You have been to Moscow, Volgograd, and Saint Petersburg

package 還提供更方便的功能 - 正確生成復數、單數名詞、序數、不定冠詞; 將數字轉換為單詞。

暫無
暫無

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

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