【问题标题】:How to distinguish same int and float elements?如何区分相同的 int 和 float 元素?
【发布时间】:2015-08-09 23:26:26
【问题描述】:

我得到了以下任务:创建一个函数,该函数将接收不同元素列表作为参数并返回原始元素列表(列表中每个元素的计数不应超过 1)。元素的顺序应该保留。如下:

[1, 1.0, '1', -1, 1] # input
[1, 1.0, '1', -1] # output

我试过了

def original_list(*a):
    b=[]    
    for i in a:
        if i not in b:
            b.append(i)
return b

但得到[1, '1', -1] 作为回报,1==1.0True。那么如何强制 Python “区分”相同值的 int 和 float 元素并获得正确的输出列表呢?

【问题讨论】:

标签: python list floating-point integer


【解决方案1】:

您还可以执行以下操作:

>>> example_list = [1, 1.0, '1', -1, 1, 1.0]
>>> output = []
>>> for item in example_list:
        indexes = [i for i, x in enumerate(output) if x==item]
        if not indexes:
            output.append(item)
        elif not filter(lambda index: type(item) == type(output[index]) , indexes):
            output.append(item)
        indexes = []

我们有一个输入列表和一个最初为空的output 列表。首先,我们迭代输入列表的每个item。我们计算output 列表中与输入列表中的item 相等的所有元素的indexes
如果indexes 列表为空,我们将item 附加到output 列表中。否则,对于output 列表中的每个索引,我们会过滤掉那些item 类型与该索引处output 列表中元素类型相同的索引。如果过滤后得到的列表为空,我们将item追加到output列表,否则该类型的item已经添加到output列表中。

迭代之后,output 列表就是我们的最终列表。

>>> output
[1, 1.0, '1', -1]

这将保留顺序并过滤掉重复项,从而忽略不同类型的唯一值。

【讨论】:

  • output.append(p) 你没有指定任何名称p
  • 抱歉,已编辑帖子。它是item 而不是p。再次检查。
  • 复杂的一个,但它有效:) 顺便说一句,这仅适用于 Python2,因为与 Python3 它返回相同的 [1, '1', -1]
【解决方案2】:

对您的解决方案稍作修改:

def original_list(a):
    b=[]    
    for i in a:
        if i not in b or not isinstance(i,int):
            b.append(i)
    return b

【讨论】:

    【解决方案3】:

    如果排序不重要,只需使用类型和集合推导即可。

    input = [1, 1.0, '1', -1, 1]
    
    output = [x[0] for x in {(y, type(y)) for y in input}]
    
    print output
    

    您可以使用相同的想法来保持顺序。

    output = []
    output_filter = set()
    for y in input:
        if (y, type(y)) not in output_filter:
            output_filter.add((y, type(y)))
            output.append(y)
    print output
    

    【讨论】:

    • 我认为这是一个扩展的答案。
    • 这假定列表元素是可散列的。例如,input = [[1], [2]] 将不起作用。
    • 是的,看起来他对原语感兴趣,而不是数据结构。如果他在不可散列的数据结构上尝试它,它将引发异常(它不会欺骗性地给出错误答案,就像基于 is 的解决方案那样。我真的想让他远离 O(n^2) 解决方案,以保护他免受大型数据集的影响。最后,整个问题并不是非常Pythonic,所以在这种情况下,这似乎是最好的答案。
    猜你喜欢
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    相关资源
    最近更新 更多