在下面的方法定义,什么是*和**为做param2?
def foo(param1, *param2):
def bar(param1, **param2):
Run Code Online (Sandbox Code Playgroud) python syntax parameter-passing variadic-functions argument-unpacking
我知道如何获得两个平面列表的交集:
b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]
Run Code Online (Sandbox Code Playgroud)
要么
def intersect(a, b):
return list(set(a) & set(b))
print intersect(b1, b2)
Run Code Online (Sandbox Code Playgroud)
但是当我必须找到嵌套列表的交集时,我的问题就开始了:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
Run Code Online (Sandbox Code Playgroud)
最后我想收到:
c3 = [[13,32],[7,13,28],[1,6]]
Run Code Online (Sandbox Code Playgroud)
你能帮我个忙吗?
*在C中具有特殊含义,就像在C中一样吗?我在Python Cookbook中看到了这样的函数:
def get(self, *a, **kw)
Run Code Online (Sandbox Code Playgroud)
您能否向我解释或指出我能在哪里找到答案(Google将*解释为外卡字符,因此我找不到满意的答案).
非常感谢你.
使用Python,我想检查一个列表是否包含另一个列表中也存在的项目/值。例如,这是我正在尝试做的事情:
list1 = ['item1','item2','item3']
list2 = ['item4','item5','item3']
if list1 contains any items also in list2:
print("Duplicates found.")
else:
print("No duplicates found.")
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,list2 包含一个在 list1 中也可以找到的项目,即“item3”。有什么方法可以检测是否发生这种情况吗?
谢谢。
我定义了两个列表的交集,如下所示:
def intersect(a, b):
return list(set(a) & set(b))
Run Code Online (Sandbox Code Playgroud)
对于三个参数,它看起来像:
def intersect(a, b, c):
return (list(set(a) & set(b) & set(c))
Run Code Online (Sandbox Code Playgroud)
我可以针对可变数量的列表推广此函数吗?
电话会看起来像:
>> intersect([1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2])
[2]
Run Code Online (Sandbox Code Playgroud)
编辑:Python只能这样实现吗?
intersect([
[1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]
])
[2]
Run Code Online (Sandbox Code Playgroud) 我有一份清单——
list_of_sets = [{0, 1, 2}, {0}]
Run Code Online (Sandbox Code Playgroud)
我想计算列表元素之间的交集。我想过这个解决方案:
a = list_of_sets[0]
b = list_of_sets[1]
c = set.intersection(a,b)
Run Code Online (Sandbox Code Playgroud)
这个解决方案有效,因为我知道列表的元素数量。(所以我可以声明尽可能多的变量,如 a、b 等)
我的问题是我无法找出另一种情况的解决方案,其中列表的元素数量未知。
注意:已经检查了使用循环计算列表元素数量而不是根据结果创建变量的想法。因为我必须将我的代码保存在一个函数中(其中参数是 list_of_sets),所以我需要一个可以用于任何编号列表的更通用的解决方案。
编辑1:
我需要列表中所有元素的解决方案。(不是成对或 3/4 元素)
我有一个n表示为的整数集合列表lst = [S1, S2, S3 ... Sn],我想找到所有集合的交集。
有没有最佳的方法来做到这一点?