【问题标题】:extract strings from list从列表中提取字符串
【发布时间】:2017-11-08 23:18:18
【问题描述】:

我有这段代码来提取图中从一个节点到另一个节点的最短路径

g = json_graph.node_link_graph(json.load(open("MPLS-topo.json")))
paths = nx.shortest_path(g, "H1", weight="weight")
for dest in paths.keys():  # Nicely output all those paths
  if dest == "H2":
    print "Shortest Path from H1 to {} is:".format(dest)
    print "{}".format(paths[dest])

它的输出是

 Shortest Path from H1 to H2 is:
 ['H1', u'S1', u'S2', u'S3', u'S5', u'H2']

我想删除你并将路径转换为这样的字符串

 H1-S1-S2-S3-S5-H2

我试过了

 path = [s.replace('u', '') for s in paths[dest]]
 print path
 y = "-".join(path)

但它给了我相同的输出。 我如何在 python 中做到这一点?

【问题讨论】:

  • 'u' 不是字符串,它表示它是 Unicode 编码的。这可以帮助你:docs.python.org/2/howto/unicode.html
  • 不用担心u。它不会影响您可以执行的字符串操作,并且如果您决定将列表写入文件,它也不会出现在文件中。就像你通常使用任何字符串列表一样使用列表

标签: python string list


【解决方案1】:

请尝试将 unicode 转换为字符串格式的编码选项:

path = [s.encode('utf-8') for s in li]
print("-".join(path))

这应该会给你想要的输出。

【讨论】:

  • 非常感谢。这很有帮助
  • 如果对您有帮助,请点赞并接受答案。
猜你喜欢
  • 1970-01-01
  • 2019-08-26
  • 2020-10-06
  • 2021-11-07
  • 2018-12-13
  • 1970-01-01
  • 2019-04-30
  • 2017-03-11
  • 2014-07-12
相关资源
最近更新 更多