有一个文件包括 str int 列表和元组。我想把它们放在不同的列表中。
这是我的示例代码:
for word in file:
if type(word) == int:
......
if type(word) == list:
......
我可以检查 int 使用 type(word) == int
但我不能在我的代码中使用 'type(word) == list'。
那么,如何检查文件是“列表”还是“元组”?
有一个文件包括 str int 列表和元组。我想把它们放在不同的列表中。
这是我的示例代码:
for word in file:
if type(word) == int:
......
if type(word) == list:
......
我可以检查 int 使用 type(word) == int
但我不能在我的代码中使用 'type(word) == list'。
那么,如何检查文件是“列表”还是“元组”?
这应该工作 -
for word in file:
if isinstance(word, int):
...
elif isinstance(word, list):
...
elif isinstance(word, tuple):
...
elif isinstance(word, str):
...
如果没有可以利用的模式来预测文件的每一行将代表什么,那么您可以提前尝试这个快速而肮脏的解决方案:
for word in file:
# Read the word as the appropriate type (int, str, list, etc.)
try:
word = eval(word) # will be as though you pasted the line from the file directly into the Python file (e.g. "word = 342.54" if word is the string "342.54"). Works for lists and tuples as well.
except:
pass # word remains as the String that was read from the file
# Find what type it is and do whatever you're doing
if type(word) == int:
# add to list of ints
elif type(word) == list:
# add to list of lists
elif type(word) == tuple:
# add to list of tuples
elif type(word) == str:
# add to list of strs
你可以使用类型
from types import *
type(word) == ListType
type(word) == TupleType
作为您的问题,您可以简单地编码为:
>>> from types import *
>>> file = [1,"aa",3,'d',[23,1],(12,34)]
>>> int_list = [item for item in file if type(item)==int]
>>> int_list
[1, 3]