📜  Python – 列出不包括重复项的产品

📅  最后修改于: 2022-05-13 01:54:55.011000             🧑  作者: Mango

Python – 列出不包括重复项的产品

本文重点介绍从包含可能重复项的列表中获取唯一列表并查找其产品的操作之一。这个操作有很大的编号。应用程序,因此它的知识是好的。
方法一:朴素的方法
在朴素的方法中,我们简单地遍历列表并将元素的第一次出现附加到新列表中,并忽略该特定元素的所有其他出现。执行产品的任务是使用循环完成的。

Python3
# Python 3 code to demonstrate
# Duplication Removal List Product
# using naive methods
 
# getting Product
def prod(val) :
    res = 1
    for ele in val:
        res *= ele
    return res 
 
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print ("The original list is : " + str(test_list))
 
# using naive method
# Duplication Removal List Product
res = []
for i in test_list:
    if i not in res:
        res.append(i)
res = prod(res)
 
# printing list after removal
print ("Duplication removal list product : " + str(res))


Python3
# Python 3 code to demonstrate
# Duplication Removal List Product
# using list comprehension
 
# getting Product
def prod(val) :
    res = 1
    for ele in val:
        res *= ele
    return res 
 
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print ("The original list is : " + str(test_list))
 
# using list comprehension
# Duplication Removal List Product
res = []
[res.append(x) for x in test_list if x not in res]
res = prod(res)
 
# printing list after removal
print ("Duplication removal list product : " + str(res))


Python3
import functools
 
functools.reduce(lambda x, y: x*y, set([1, 3, 5, 6, 3, 5, 6, 1]), 1)


输出 :
The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
Duplication removal list product : 90


方法 2:使用列表推导
此方法的工作原理与上述方法类似,但这只是在列表理解的帮助下完成的较长方法的单行简写。

Python3

# Python 3 code to demonstrate
# Duplication Removal List Product
# using list comprehension
 
# getting Product
def prod(val) :
    res = 1
    for ele in val:
        res *= ele
    return res 
 
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print ("The original list is : " + str(test_list))
 
# using list comprehension
# Duplication Removal List Product
res = []
[res.append(x) for x in test_list if x not in res]
res = prod(res)
 
# printing list after removal
print ("Duplication removal list product : " + str(res))
输出 :
The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
Duplication removal list product : 90

方法 3:使用 set() 和 functools.reduce() [中级]

检查列表成员的平均时间为 O(n),因此建立非重复列表的操作平均为 O(n 2 )。可以将列表转换为一组以删除重复项,这是 O(n) 复杂度。在此之后,可以通过迭代它们以通常的方式计算集合元素的乘积,或者为了进一步减少代码,可以使用 functools 模块中的 reduce() 方法。正如文档所解释的:

这是如何将代码减少到几行的方法

Python3

import functools
 
functools.reduce(lambda x, y: x*y, set([1, 3, 5, 6, 3, 5, 6, 1]), 1)

这样做是将 lambda 应用于从列表中获得的集合。 lambda 接受两个参数 x 和 y 并返回两个数字的乘积。此 lambda 累积应用于列表中的所有元素,即

最终结果为 90。在 reduce()函数中添加初始参数以处理空序列以便返回默认值始终是谨慎的。在这种情况下,因为它是一个产品,所以该值应该是 1。因此类似于

产生输出 1,尽管列表为空。这个初始参数被添加到序列中的值之前,并且像往常一样应用 lambda。