【问题标题】:how to check str int list and tuple? [closed]如何检查 str int 列表和元组? [关闭]
【发布时间】:2013-04-08 04:55:06
【问题描述】:

有一个文件包括 str int 列表和元组。我想把它们放在不同的列表中。

这是我的示例代码:

for word in file:
    if type(word) == int:
        ......
    if type(word) == list:
        ......

我可以检查 int 使用 type(word) == int

但我不能在我的代码中使用 'type(word) == list'。

那么,如何检查文件是“列表”还是“元组”?

【问题讨论】:

  • 您从文本文件中读出的所有内容都是str。你到底想做什么?

标签: python string list class python-3.x


【解决方案1】:

如果没有可以利用的模式来预测文件的每一行将代表什么,那么您可以提前尝试这个快速而肮脏的解决方案:

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】:

    这应该可行-

    for word in file:
        if isinstance(word, int):
            ...
        elif isinstance(word, list):
            ...
        elif isinstance(word, tuple):
            ...
        elif isinstance(word, str):
            ...
    

    【讨论】:

    • 您通过迭代file 获得的所有word 都将是字符串。如果我没记错的话,只有elif isinstance(word,str) 这行实际上会评估为True
    【解决方案3】:

    你可以使用类型

    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]
    

    【讨论】:

    • 我试过了,但它不起作用。我正在使用 python shell。
    • @Vinceeema 那么你能举一个你的“文件”变量的例子吗?我认为这是一个可迭代的对象,其中包含 str int 列表和元组。比如pickle.load的结果
    猜你喜欢
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多