gpt4 book ai didi

python - 名单有编号吗?

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:28 25 4
gpt4 key购买 nike

我有一个列表:

my_list = [12,8,0,4,7,21,27,"O",29,3,"X","O","X","X"]

此列表会在整个程序中更新。每次更新时,我都想检查它是否仅包含数字或仅包含字符串,或两者兼而有之。我可以用什么来做到这一点?我需要检查列表中的所有元素。有什么建议吗? **

**请解释代码的工作原理。

谢谢大家的帮助。感谢您的帮助。

最佳答案

如何使用 typeset :

>>> my_list = [12,8,0,4,7,21,27,"O",29,3,"X","O","X","X"]
>>> set(map(type, my_list))
{<class 'int'>, <class 'str'>}
>>> set(map(type, my_list)) == {int, str}
True
>>> set(map(type, my_list)) == {int}
False
>>> set(map(type, my_list)) == {str}
False

>>> my_list = [12,8,0,4,7,21,27]
>>> set(map(type, my_list))
{<class 'int'>}

>>> my_list = ["X", "O", "X", "X"]
>>> set(map(type, my_list))
{<class 'str'>}
>>> set(map(type, my_list)) == {str}
True

type 返回对象的类型:

>>> type(1)
<class 'int'>
>>> type('X')
<class 'str'>

map(type, seq)type 应用于seq:

>>> map(type, [1, 2, 3, 'X'])
<map object at 0x7fc763de6e90>
>>> list(map(type, [1, 2, 3, 'X']))
[<class 'int'>, <class 'int'>, <class 'int'>, <class 'str'>]
>>> # Using `set`, you can get unique types.
>>> set(map(type, [1, 2, 3, 'X']))
{<class 'int'>, <class 'str'>}

注意(@lvc 的评论)

This will break if you happen to have subclases of int or str in the list. This is probably unlikely with those classes specifically, but it means it doesn't generalise very well.

关于python - 名单有编号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20041694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com