【问题标题】:How can I separate list values on the basis of type - Python [closed]如何根据类型分隔列表值 - Python [关闭]
【发布时间】:2019-01-28 11:30:20
【问题描述】:

从包含整数、字符串和浮点数的列表中,创建三个列表以分别存储它们。

请帮助我如何根据类型分隔列表值。

【问题讨论】:

  • 你的代码哪里出了问题?
  • >>> from collections import defaultdict >>> d = defaultdict(list) >>> lst = [1, 'a', 2.0, 2] >>> for v in lst: ... d[type(v).__name__].append(v) ... >>> d defaultdict(<class 'list'>, {'int': [1, 2], 'str': ['a'], 'float': [2.0]})
  • 看看isinstance内置函数。
  • 大家好,感谢您的建议和回复。这是我的第一篇文章,所以我不太了解它,下次我改进我的问题。

标签: python python-3.x list


【解决方案1】:

你可以使用类型。

test = [3, "hello", 2.4]

int_array = []
string_array = []
float_array = []

for value in test:
    check = type(value)
    if check == int:
        int_array.append(value)
    elif check == str:
        string_array.append(value)
    elif check == float:
        float_array.append(value)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多