【问题标题】:evaluate a list in one line code in python [duplicate]在python中用一行代码评估一个列表[重复]
【发布时间】:2020-11-29 06:52:15
【问题描述】:

我创建了一个函数来评估列表是否有重复:

def duplica(list_to_check):
    if len(set(list_to_check)) != len(list_to_check):
        print('there are duplicates inside the list')
        result = 0  
    else:
        result = 1
    
    return result

print(duplica([1, 1, 2]))

##test it:
there are duplicates inside the list 
0

我想知道是否有其他方法可以使用仅一行代码(例如 lambda 或 map)来评估列表

【问题讨论】:

  • 不,它不回答
  • 确实如此。

标签: python


【解决方案1】:

如果你只需要值:

0 if len(set(list_to_check)) != len(list_to_check) else 1

甚至更好():(评论中提供:Olvin Roght

int(len(set(list_to_check)) == len(list_to_check))

带打印:

(0,print('there are duplicates inside the list'))[0] if len(set(list_to_check)) != len(list_to_check) else 1

【讨论】:

  • Bool 可以作为整数在运算中正常使用,所以你甚至不需要int()
【解决方案2】:

你可以这样做:

def check_duplicates(items):
    return len(set(items)) == len(items)
    # return len(items) - len(set(items)) # if you need a number


if __name__ == '__main__':
    test = [11, 21, 3, 11, 2]
    print(f'There are duplicates inside the list:\n{int(check_duplicates(test))}')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    相关资源
    最近更新 更多