有一个文件包括str int list和tuple。我想把它们放在不同的列表中。
这是我的示例代码:
for word in file:
if type(word) == int:
......
if type(word) == list:
......
我可以检查int use type(word)== int
但我不能在我的代码中使用'type(word)== list'。
那么,如何检查文件是'list'还是'tuple'?
答案 0 :(得分:2)
这应该有效 -
for word in file:
if isinstance(word, int):
...
elif isinstance(word, list):
...
elif isinstance(word, tuple):
...
elif isinstance(word, str):
...
答案 1 :(得分:0)
如果没有模式可以利用来预测文件的每一行代表什么,提前你可以试试这个快速而肮脏的解决方案:
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
答案 2 :(得分:-2)
您可以使用类型
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]