簡體   English   中英

當涉及到 Python 中的 return 語句時,you.format 如何?

[英]How do you .format when it comes to return statements in Python?

def 預算(購物:[無])-> str:

這是我的清單:

shopping = ['1', ('242','18'), ('13','1'),('349','2')]

我想讓它成為 function 的參數,並有一個返回語句,當打印時,它會產生這個:

Shopping Budget: Week 1 
Day = 242, Items = 18
Day = 13, Items = 1
Day = 349, Items = 2

我正在努力正確格式化它,因為我的 for 循環會連同它一起打印“購物預算”。

我希望能夠用我列表中的任何數字返回這個 function。

鑒於沒有提供 function,並且提到循環,我假設您正在嘗試循環shopping的內容並格式化發布的響應。

您可以在下面這樣做,前提是shopping清單完全遵循相同的格式。

shopping = ['1', ('242','18'), ('13','1'),('349','2'), '2', ('1', '2'), ('3', '3'), ('4', '4')]
for week in shopping:
    if type(week) == str:
        print(f'Shopping Budget: Week {week}')
    else:
        print(f'Day = {week[0]}, Items = {week[1]}')

解釋


  1. for week in shopping:遍歷shopping清單中的每個元素
  2. if type(week) == str:如果元素是str類型
  3. print(f'Shopping Budget: Week {week}')使用f-strings用字符串值格式化字符串
  4. else假設可迭代print(f'Day = {week[0]}, Items = {week[1]}')使用f-strings來格式化元組值

Output

Shopping Budget: Week 1
Day = 242, Items = 18
Day = 13, Items = 1
Day = 349, Items = 2
Shopping Budget: Week 2
Day = 1, Items = 2
Day = 3, Items = 3
Day = 4, Items = 4

注釋和建議

您的購物清單並沒有很好地存儲數據。 如果將另一個不是一周的元素存儲為字符串,則檢查元素的類型以指示一周的更改可能會導致問題。

您應該為此使用dictionary ,它會更加清晰和簡潔。

shopping = {
    '1': {
        'day': 242,
        'items': 18
        },
    '2': {
        'day': 25,
        'items': 9
        },  
    }

shopping['1']['day']

我將打印第一個元素,然后遍歷 rest 並使用 f 字符串(請參閱: https://realpython.com/python-f-strings/

shopping = ['1', ('242','18'), ('13','1'),('349','2')]
print(f"Shopping Budget: Week {shopping[0]}")

for shopping_info in shopping[1:]:
  print(f"Day = {shopping_item[0]}, Items = {shopping_item[1]}")

我做了與@PacketLoss 相同的操作,但我使用.format並檢查了tuple類型。

shopping = ['1', ('242','18'), ('13','1'),('349','2')]


def budget(shopping=[None]) -> str:

    for element in shopping:

        if not isinstance(tuple, element):

            print('Week {}'.format(element))

        else:
            print('Day {}  Items: {}'.format(element[0], element[1]))

budget(shopping)

暫無
暫無

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

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