如何在 Python 中打印不带括号的元组列表 [英] How to print a list of tuples with no brackets in Python

查看:46
本文介绍了如何在 Python 中打印不带括号的元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种从没有括号的元组中打印元素的方法.

I'm looking for a way to print elements from a tuple with no brackets.

这是我的元组:

mytuple = [(1.0,),(25.34,),(2.4,),(7.4,)]

我将其转换为列表以使其更易于使用

I converted this to a list to make it easier to work with

mylist = list(mytuple)

然后我做了以下

for item in mylist:
    print(item.strip())

但我收到以下错误

AttributeError: 'tuple' object has no attribute 'strip'

这很奇怪,因为我以为我已转换为列表?

Which is strange because I thought I converted to a list?

我希望看到的最终结果类似于:

What I expect to see as the final result is something like:

1.0,
25.34,
2.4,
7.4

1.0, ,23.43, ,2.4, ,7.4 

推荐答案

mytu​​ple 已经是一个列表(元组的列表),所以调用 list() 就可以了什么都不做.

mytuple is already a list (a list of tuples), so calling list() on it does nothing.

(1.0,) 是一个包含一项的元组.你不能在它上面调用字符串函数(就像你试过的那样).它们用于字符串类型.

(1.0,) is a tuple with one item. You can't call string functions on it (like you tried). They're for string types.

要打印元组列表中的每个项目,只需执行以下操作:

To print each item in your list of tuples, just do:

for item in mytuple:
    print str(item[0]) + ','

或者:

print ', ,'.join([str(i[0]) for i in mytuple])
# 1.0, ,25.34, ,2.4, ,7.4

这篇关于如何在 Python 中打印不带括号的元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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