[英]How to join list from th yaml file in python
How to Join the list based on YAML
file, i have below file which need to join by space delimitation.如何根据
YAML
文件加入列表,我有以下文件需要通过空格分隔加入。
$ cat File.yml
---
fruits:
- orange
- banana
- apple
- strawberry
- berry
- cherry
...
>>> import yaml
>>> with open('File.yml') as f:
... result = yaml.safe_load(f)
... print(result)
...
{'fruits': ['orange', 'banana', 'apple', 'strawberry', 'berry', 'cherry']}
Can we do something {{ fruits[ item ] | join(' ') }}"
我们能不能做点什么
{{ fruits[ item ] | join(' ') }}"
{{ fruits[ item ] | join(' ') }}"
? {{ fruits[ item ] | join(' ') }}"
?
"orange banana apple strawberry berry cherry"
I don't require ","
in the result.结果中不需要
","
。
Just try this:试试这个:
import yaml
with open('File.yml') as f:
result = yaml.safe_load(f)
print(' '.join(result['fruits']))
Output:输出:
orange banana apple strawberry berry cherry
Just going on top of what you already have.只是在你已经拥有的之上。
>>> with open("File.yml") as f:
... result = yaml.safe_load(f)
>>> " ".join(result["fruits"])
"orange banana apple strawberry berry cherry"
You can refer to the Python docs for a more in-depth description on the syntax of the .join
.您可以参考Python 文档以获取有关
.join
语法的更深入描述。 The gist of it is that we need它的要点是我们需要
str.join(iterable)
In this case, we want to join by empty spaces, " "
, and we want to iterate through the contents of result["fruits"]
" to join the items into one string.在这种情况下,我们希望通过空格
" "
,并且我们希望遍历result["fruits"]
" 的内容以将项目连接成一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.