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

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

问题描述

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

How can I remove the comma from each tuple in the list.
I want to make a list of tuples from one 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 of l2 to just this:

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

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

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