combine list of lists in python (similar to string.join but as a list comprehension?)
本问题已经有最佳答案,请猛点这里访问。
如果您有一个格式为
我是这样做的:
1 2 3 4 | this_list = [['A',1,2],['B',3,4]] final = list() for x in this_list: final.append(', '.join([str(x) for x in x])) |
但这是否可以作为一条线来完成呢?
谢谢你的回答。我喜欢基于map()的。我还有一个后续问题——如果子列表不是格式
再加上我那丑陋的代码,它会是:
1 2 3 4 5 | this_list = [['A',0.111,0.12345],['B',0.1,0.2]] final = list() for x in this_list: x = '{}, {:.1f}, {:.2f}'.format(x[0], x[1], x[2]) final.append(x) |
我解决了自己的问题:
1 | values = ['{}, {:.2f}, {:.3f}'.format(c,i,f) for c,i,f in values] |
1 2 3 | >>> lis = [['A',1,2],['B',3,4]] >>> [', '.join(map(str, x)) for x in lis ] ['A, 1, 2', 'B, 3, 4'] |
您可以在
1 2 3 4 | >>> lst = [['A',1,2],['B',3,4]] >>> [",".join([str(y) for y in x]) for x in lst] ['A, 1, 2', 'B, 3, 4'] >>> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | li = [['A',1,2],['B',3,4],['A',0.111,0.123456]] print [', '.join(map(str,sli)) for sli in li] def func(x): try: return str(int(str(x))) except: try: return '%.2f' % float(str(x)) except: return str(x) print map(lambda subli: ', '.join(map(func,subli)) , li) |
返回
1 2 | ['A, 1, 2', 'B, 3, 4', 'A, 0.111, 0.123456'] ['A, 1, 2', 'B, 3, 4', 'A, 0.11, 0.12'] |