[英]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.