python - 以根据值具有不同格式的格式化方式打印值?
问题描述
我对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()
函数将提供一个迭代器,该迭代器一次动态地返回一个对象,并且不能回溯。如果您随后将迭代器分配给变量并在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'
您需要为此添加错误处理以处理边缘情况,但这应该可以解决您的直接问题。
推荐阅读
- list - 用语义等效的猫功能替换 scalaz ListT
- c# - 是否有一种面向 LINQ 的方法来快速评估字典中的嵌套列表
- c# - 如何在 ASPNET Core 3.0 中启动后台进程?
- python - pandas 中带有 groupby 的多个条件语句
- c# - 如何在 C# 项目中包含 C# .dll 包装器?
- pandas - 合并 Pandas 数据框
- python - Matplotlib:每条线具有不同组的折线图
- microsoft-graph-api - 有没有办法将 microsoft graph API 中的管理员用户 accountEnabled 状态更新为 OAuth 应用程序
- sql - 使用 Sql 对不同组的用户进行不同的配对
- flask-wtforms - 我应该如何将 css 类添加到 Flask wtform“标签”