【问题标题】:How to print list items with their type previous text?如何打印列表项及其类型的先前文本?
【发布时间】:2020-12-02 09:12:57
【问题描述】:

我有一个包含不同类型项目的列表,例如: list = [2137, 11.22, 3+4j, True, 'nationality', (0, -99), [4, 18], {"class":'A', "section":'3'}] 我想逐行打印列表项,添加有关字母项类型的信息 类似的东西:

2137 是类型:int

【问题讨论】:

  • 您在打印这些项目时是否尝试过使用type()

标签: python list printing items


【解决方案1】:

使用循环试试这个:

for i in list: 
    print(i, type(i))

输出将是:

2137 <class 'int'>
11.22 <class 'float'>
(3+4j) <class 'complex'>
True <class 'bool'>
nationality <class 'str'>
(0, -99) <class 'tuple'>
[4, 18] <class 'list'>
{'class': 'A', 'section': '3'} <class 'dict'>

你也可以在一行中做到这一点:

print(*zip(list,map(type,list)),sep='\n')

请注意:

不要使用list 作为变量名。 list 是在 python 中预定义的。

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多