Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从数组中选择最大值_Python_Arrays_List_Max - Fatal编程技术网

Python 从数组中选择最大值

Python 从数组中选择最大值,python,arrays,list,max,Python,Arrays,List,Max,如何获取列表中具有最大长度的子列表 我有以下代码: c = [1,2] a = [[1,2], [3,4], [3,2]] for b in a: g = len(list(set(b) - set(c))) *#list of difference items between c and b in a* print(g) 结果 0 2 1 我需要在a中获得长度最长的bg=2 我曾经 y = [b for b in a if max (g)] TypeError:“int”

如何获取列表中具有最大长度的子列表

我有以下代码:

c = [1,2]
a = [[1,2], [3,4], [3,2]]
for b in a:
    g = len(list(set(b) - set(c))) *#list of difference items between c and b in a*
    print(g)
结果

0
2
1
我需要在
a
中获得长度最长的
b
g=2

我曾经

y = [b for b in a if max (g)]
TypeError:“int”对象不可编辑

谢谢,

max(g)
没有什么意义,因为
g
只是上一个循环中最后一个
int
值(
1
max()
需要一个iterable,因此会出现错误。但是,即使将
g
固定为列表
[0,2,1]
你在列表理解中的守卫也不会真正做任何事情,因为它总是计算为
True
,因为它相当于编写
if 2

但您可以使用
max()
重写代码,使用
键来计算差异:

>>> c = [1,2]
>>> a = [[1,2], [3,4], [3,2]]
>>> max(a, key=lambda x: len(set(x)-set(c)))
[3, 4]
你可以试试这个

c = [1,2]
a = [[1,2], [3,4], [3,2]]
k=max(max(map(lambda x:set(c)-set(x),a)))
print k if k else 0