从数组python中选择最大值

时间:2017-04-19 04:59:54

标签: python arrays list max

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

我有这个代码:

public class Client2 {
private static final String server = "localhost";
private static final int port = 1111;
private static final String filePath = "medianFile.txt";
private static final String fileName = "medianFile.txt";
private static final String CAcert = "CA.crt";

public static void main(String[] args) {
    try{
        Socket socket = new Socket(server,port);
        OutputStream byteOut = socket.getOutputStream();
        InputStream byteIn = socket.getInputStream();

        PrintWriter stringOut = new PrintWriter(socket.getOutputStream(),true);
        BufferedReader stringIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        stringOut.println("Please prove ur identity!");
        stringOut.flush();
        System.out.println("Sent to server: Please prove ur identity!");

        String r1 = stringIn.readLine();
        System.out.println(r1);

//          send nonce
        byte[] nonce = generateNonce();
        if(r1.contains("I am server")){
            stringOut.println(Integer.toString(nonce.length));
            byteOut.write(nonce);
            byteOut.flush();
            System.out.println("Sent to server: nonce sent!");
        }

//          get encrypted nonce from server
        String encryptedNonceLen = stringIn.readLine();
        byte[] encryptedNonceBytes = new byte[Integer.parseInt(encryptedNonceLen)];
        readByte(encryptedNonceBytes,byteIn,socket);
    }
}

结果

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 b a {»长度>>> g = 2

我用过

y = [b for b in a if max (g)]

TypeError: 'int' object is not iterable

谢谢,

2 个答案:

答案 0 :(得分:4)

max(g)并没有多大意义,因为g只是前一个循环中的最后一个int值(1)。 max()期望迭代 - 因此你的错误。但即使将g修改为列表理解中的后卫列表[0, 2, 1]也不会真正做任何事情,因为它总是会评估为True,因为它等同于写if 2 }。

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

>>> c = [1,2]
>>> a = [[1,2], [3,4], [3,2]]
>>> max(a, key=lambda x: len(set(x)-set(c)))
[3, 4]

答案 1 :(得分:0)

你可以尝试这个

$conn = mysql_connect($server,$user,$password );
if (!$conn) {
    die('Not connected : ' . mysql_error());
}

$db_selected = mysql_select_db($dbName, $conn);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}