python - Python逗号用于循环条件逗号分隔
问题描述
我想,当我for循环时,每个项目的末尾都会有逗号,除了最后一项,最后一项应该是点
x = ['df', 'second', 'something', 'another']
separator = ''
for i in x:
r = i
print(r, separator)
separator = ','
else:
separator = '.'
这是我当前的代码。
我的预期结果应该如下所示:
df,
second ,
something ,
another.
在这种情况下谁能帮助我?
解决方案
使用enumerate
前任:
x = ['df', 'second', 'something', 'another']
l = len(x)-1
for i, v in enumerate(x):
if i != l:
print(v, ",")
else:
print(v.strip()+".")
输出:
df ,
second ,
something ,
another.
或者如果你想在单行逗号分隔使用它
print(", ".join(x) + ".") # -->df, second, something, another.
推荐阅读
- reactjs - 使用 mobx-react 注入嵌套组件
- ios - 如果我以编程方式进行所有布局,是否需要启用基本国际化?
- reactjs - react.js 中的 onClick 事件出错
- javascript - 未捕获的 ReferenceError:未定义 getLocation
- python - uwsgi和bottle中存在文件,但是出现404错误
- python - 将字符串数据转换为数值数据
- git - 在 Cygwin 中通过 SSH 进行 Git 克隆不提示输入密码,而是输出错误
- ruby-on-rails - 如何为 Rails 5.2 转换 Rails 动态路由
- go - 当端口在.json文件中硬编码时如何使用动态端口?
- php - laravel 自动硬删除