【问题标题】:print python list of lists into string将python列表列表打印成字符串
【发布时间】:2012-12-01 03:12:28
【问题描述】:

我有列表列表:

[['lorem', ['a', 'b', 'c', 'd']], ['ipsum', ['e']], ['dolor', ['f','g']], ['sit', ['h', 'i']]]

如何实现这一点?

lorem (a + b + c + d); ipsum (e); dolor (e + g); sit (h + i)

到目前为止,我已经尝试过:

print '\n'.join('%s %s' % x for x in list) 

没有运气。

【问题讨论】:

  • print '\n'.join('%s %s' % x for x in list) 不走运

标签: python list dictionary tuples


【解决方案1】:
In [14]: L = [['lorem', ['a', 'b', 'c', 'd']], ['ipsum', ['e']], ['dolor', ['f', 'g']], ['sit', ['h', 'i']]]

In [15]: '; '.join("%s (%s)" %(elem[0], " + ".join(elem[1])) for elem in L)
Out[15]: 'lorem (a + b + c + d); ipsum (e); dolor (f + g); sit (h + i)'

In [18]: L = [(e[0], " + ".join(e[1])) for e in L]

In [19]: L
Out[19]: 
[('lorem', 'a + b + c + d'),
 ('ipsum', 'e'),
 ('dolor', 'f + g'),
 ('sit', 'h + i')]

In [20]: '; '.join("%s (%s)" %(e[0], e[1]) for e in L)
Out[20]: 'lorem (a + b + c + d); ipsum (e); dolor (f + g); sit (h + i)'

【讨论】:

  • 不错的答案,非常有效的方法。
猜你喜欢
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 2018-01-13
相关资源
最近更新 更多