簡體   English   中英

以根據值具有不同格式的格式化方式打印值?

[英]Printing values in a formatted way that has different formats depending on value?

我對 python 還是比較陌生,只是想知道如何從一個函數打印值,該函數接受一個列表作為輸入,並打印每個值,每個值用逗號分隔,每兩個值除了 -1 它只是自己打印(假設有如果不是 -1,則總是將兩個值匹配在一起)。

一些例子是:輸入: [2,3,4,2,-1,4,3]輸出: 2 3, 4 2, -1, 4 3

輸入: [2,1,-1]輸出: 2 1, -1

每次解決方案時,我都覺得我用 while 循環和 if 語句想多了。 無論如何,這是否會更快更容易?

對於您可能需要在一次迭代中從列表中獲取多個元素的情況,迭代器通常是一種可行的解決方案。 在任何可迭代對象(列表、字符串、字典、生成器iter()上調用內置的iter()將提供一個迭代器,它一次返回一個對象,動態地,並且不能回溯 如果然后將迭代器分配給變量並在for循環中使用該變量,則可以自己有選擇地調用next()以使循環“跳過”元素:

inp = [2,3,4,2,-1,4,3]
inp_iter = iter(inp)
output = []
for elem in inp_iter:  # each iteration essentially calls next() on the iterator until there is no more next()
    if elem == -1:
        output.append(str(elem))
    else:
        # withdraw the next element from the iterator before the `for` loop does automatically
        # thus, the for loop will skip this element
        next_elem = next(inp_iter)
        output.append(f"{elem} {next_elem}")
print(', '.join(output))
# '2 3, 4 2, -1, 4 3'

您需要為此添加錯誤處理以處理邊緣情況,但這應該可以解決您的直接問題。

暫無
暫無

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

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