python - 如何用破折号替换嵌套的短语列表?

标签 python list nested

如果我有

LIST=[['SPORTS','NEW YORK JETS']]

并且我想将子列表的第二个元素 (NEW YORK JETS) 替换为 ___ ____ ____ ,我该怎么做?

到目前为止,我已经:

hide = ""
for l in LIST:
 if l[1] != " ":
  hide = hide + "_"
else:
  hide = hide + " "
print(hide)

这没有给我想要的输出。如果有任何建议,我将不胜感激。

谢谢!

最佳答案

您必须在嵌套循环中循环遍历字符串中的字符,并将非空格字符替换为 _

result = []
for word1, word2 in LIST:
    hide = ""
    for c in word2:
        if c == " ":
            hide += " "
        else:
            hide += "_"
    result.append([word1, hide])

关于python - 如何用破折号替换嵌套的短语列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60355474/

相关文章:

python - 如何检查具有多个列表的 pandas 列中的项目是否重复?

python - 运行时错误 : PytorchStreamReader failed locating file data. pkl:找不到文件

c# - 为什么 List<Object> 的 find 和 findindex 痛苦缓慢?

python - 打印列表返回每个元素的位置,而不是值

python - 使用 scipy/simplex 进行线性优化不能提供最佳效果

python - Selenium:退出Python脚本而不关闭浏览器

c# - 统一列表 (C#)

VBA EXCEL 多个嵌套 FOR 循环,为表达式设置两个变量

c++ - 与 C++/OpenMP 的所有相对所有比较的对称性并行化嵌套 for 循环

Excel嵌套错误