![](/img/trans.png)
[英]more pythonic way to format a JSON string from a list of tuples
[英]is there a more 'pythonic' way to generate a string from a list with customized separators
我想知道是否有比下面的方法更能从列表中生成字符串的 Pythonic 方法。
免责声明:我是一名生物物理学家,对 Python 没有深入的了解,但确实搜索并测试了以下组合: .format(a) / ([a]) / (*a) / (x for x in a)
resid {}
或.format(a) / ([a]) / (*a) / (x for x in a)
广泛,但可能我不知道要寻找什么......我知道下面的代码有效,但我不明白为什么列出的任何一个都没有。
输入:
a=[23,33,105,400]
代码:
c=""
for x in a[0:-1]:
c = c + "resid {} or ".format(x)
c=c+"resid {}".format(a[-1])
print(c)
输出:
resid 23 or resid 33 or resid 105 or resid 400
使用字符串连接
" or ".join("resid {}".format(x) for x in [23,33,105,400])
# 'resid 23 or resid 33 or resid 105 or resid 400'
您还可以使用 f 字符串
" or ".join(f'resid {x}' for x in [23,33,105,400])
您可以按如下方式创建格式字符串:
format_string = (len(a)-1) * 'resid {} or ' + 'resid {} '
然后通过以下方式对其应用 a:
print(format_string.format(*a))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.