Python:如何从元组中删除最后一个逗号 [英] Python: How to remove the last comma from tuples

查看:321
本文介绍了Python:如何从元组中删除最后一个逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从列表中的每个元组中删除逗号. 我想从1个列表中创建一个元组列表,像这样:

How can I remove the comma from each tuple in the list. I want to make a list of tuples from 1 list, like this:

l = [1,2,3,5,4]

l1 = [ ]

l2 =  [ ]

for i in l:

    l1.append (i)
    t = tuple(l1)
    l2.append(t)
    l1 = []

print l2

预期结果:

[(1), (2), (3), (5), (4)]

实际结果:

[(1,), (2,), (3,), (5,), (4,)]

推荐答案

如果只希望显示列表中每个元组的第一个元素(不带逗号),则可以始终使用以下方式手动设置输出的格式:

If you only want the first element of each tuple in the list displayed (without a comma), you can always manually format the output by using something like this:

l = [1, 2, 3, 5, 4]
l1 = []
l2 = []
for i in l:
    l1.append(i)
    t = tuple(l1)
    l2.append(t)
    l1 = []

print '[' + ', '.join('({})'.format(t[0]) for t in l2) + ']'

输出:

[(1), (2), (3), (5), (4)]

顺便说一句,您也可以将l2的构造缩短为:

BTW, you could also shorten the construction ofl2to just this:

l2 = [tuple([value]) for value in l]

这篇关于Python:如何从元组中删除最后一个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆