[英]Is there a way to print a list that moves to a new line after specific items in the list?
我想制作一個程序,可以打印出一條信息,然后打印出與第一個信息相關的另一條信息。 我有一個清單:
householdDecor= ['Potted Plant', 24.00, 'Painting', 35.30, 'Vase', 15.48,
'Rug', 49.99, 'Fancy Bowl', 28.00]
我想要它,所以當我打印列表時,它會在每個數字之后移動到新行。 所以它看起來像這樣:
Potted Plant 24.00
Painting 35.30
Vase 15.48
Rug 49.99
Fancy Bowl 28.00
有沒有辦法做到這一點,而不是像你一樣移動每個項目的行: print(householdDecor, sep = "\n")
?
做到這一點的正確方法是擁有一個包含兩個tuple
的list
,而不是一個含義因索引而異的平面list
。
幸運的是,從您擁有的形式轉換為您想要的形式並不難:
for item, price in zip(householdDecor[::2], householdDecor[1::2]):
print(item, price)
您只需將偶數和奇數元素分開切片, zip
將它們組合在一起以形成對,然后將它們print
成對(隱式放入換行符)。
一個看起來更神奇,但更高效的版本是:
for item, price in zip(*[iter(householdDecor)]*2):
print(item, price)
它使用zip
從list
上的單個迭代器中一次提取兩個項目,而無需切片(避免額外的臨時對象)。
householdDecor= ['Potted Plant',24.00,'Painting',35.30,'Vase',15.48,'Rug',49.99,'Fancy Bowl',28.00]
for i in range(len(householdDecor)):
if i%2==0:
print('\n',end=' ')
print(householdDecor[i],end=' ')
Output
Potted Plant 24.0
Painting 35.3
Vase 15.48
Rug 49.99
Fancy Bowl 28.0
@shadowranger 已經提供了兩種很好的方法來將列表切片和切割成元組列表。
另一種可能更容易理解的方法(盡管本身並不更好):
householdDecor= ['Potted Plant',24.00,'Painting',35.30,'Vase',15.48,'Rug',49.99,'Fancy Bowl',28.00]
for item, price in [householdDecor[i:i+2] for i in range(0, len(householdDecor), 2)]: # step 2
print(item, price)
另外,請注意,如果您真的只是打印數據,請考慮以下內容:
print(f'{item:20}{price:>6}')
您可以使用通用助手 function 來完成它,它可以讓您遍歷序列是兩個一組:
def pairwise(iterable):
"s -> [[s0,s1], [s1,s2], [s2, s3], ...]"
a, b = iter(iterable), iter(iterable)
next(b, None)
return zip(a, b)
for pair in pairwise(householdDecor):
print(pair[0], pair[1])
這可以進一步抽象為不同的組大小,如下所示:
def grouper(n, iterable):
"s -> (s0,s1,s2,...sn-1), (sn,sn+1,sn+2,...s2n-1), (s2n,s2n+1,s2n+2,...s3n-1), ..."
return zip(*[iter(iterable)]*n)
for pair in grouper(2, householdDecor):
print(pair[0], pair[1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.