Skip to main content
 首页 » 编程设计

python之名单有编号吗

2025年05月04日13birdshome

我有一个列表:

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

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

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

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

请您参考如下方法:

如何使用 type和 set :

>>> 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.