Преобразовать список списков в словарь

Здесь много элегантных и эффективных ответов. Но краткость может заставить нас потерять какую-то полезную информацию. В частности, часто не хочется рассматривать ошибку соединения как «Исключение», и можно было бы по-разному относиться к каким-либо связанным с сетью ошибкам - например, решить, следует ли повторить загрузку.

Вот метод, который не вызывает исключения для сетевых ошибок (только для действительно исключительных проблем, таких как неверный URL-адрес или проблемы с записью в файл)

/**
 * Downloads from a (http/https) URL and saves to a file. 
 * Does not consider a connection error an Exception. Instead it returns:
 *  
 *    0=ok  
 *    1=connection interrupted, timeout (but something was read)
 *    2=not found (FileNotFoundException) (404) 
 *    3=server error (500...) 
 *    4=could not connect: connection timeout (no internet?) java.net.SocketTimeoutException
 *    5=could not connect: (server down?) java.net.ConnectException
 *    6=could not resolve host (bad host, or no internet - no dns)
 * 
 * @param file File to write. Parent directory will be created if necessary
 * @param url  http/https url to connect
 * @param secsConnectTimeout Seconds to wait for connection establishment
 * @param secsReadTimeout Read timeout in seconds - trasmission will abort if it freezes more than this 
 * @return See above
 * @throws IOException Only if URL is malformed or if could not create the file
 */
public static int saveUrl(final Path file, final URL url, 
  int secsConnectTimeout, int secsReadTimeout) throws IOException {
    Files.createDirectories(file.getParent()); // make sure parent dir exists , this can throw exception
    URLConnection conn = url.openConnection(); // can throw exception if bad url
    if( secsConnectTimeout > 0 ) conn.setConnectTimeout(secsConnectTimeout * 1000);
    if( secsReadTimeout > 0 ) conn.setReadTimeout(secsReadTimeout * 1000);
    int ret = 0;
    boolean somethingRead = false;
    try (InputStream is = conn.getInputStream()) {
        try (BufferedInputStream in = new BufferedInputStream(is); OutputStream fout = Files
                .newOutputStream(file)) {
            final byte data[] = new byte[8192];
            int count;
            while((count = in.read(data)) > 0) {
                somethingRead = true;
                fout.write(data, 0, count);
            }
        }
    } catch(java.io.IOException e) { 
        int httpcode = 999;
        try {
            httpcode = ((HttpURLConnection) conn).getResponseCode();
        } catch(Exception ee) {}
        if( somethingRead && e instanceof java.net.SocketTimeoutException ) ret = 1;
        else if( e instanceof FileNotFoundException && httpcode >= 400 && httpcode < 500 ) ret = 2; 
        else if( httpcode >= 400 && httpcode < 600 ) ret = 3; 
        else if( e instanceof java.net.SocketTimeoutException ) ret = 4; 
        else if( e instanceof java.net.ConnectException ) ret = 5; 
        else if( e instanceof java.net.UnknownHostException ) ret = 6;  
        else throw e;
    }
    return ret;
}
2
задан martineau 17 January 2019 в 02:06
поделиться

1 ответ

Для понимания цикла и списка:

x = [['A', 'B', 'C'],
[100, 90, 80],
[88, 99, 111],
[45, 56, 67],
[59, 61, 67],
[73, 79, 83],
[89, 97, 101]]
dict1={}

for i,k in  enumerate( x[0]):
    dict1[k]=[x1[i] for x1 in x[1:]]
print(dict1)
#{'A': [100, 88, 45, 59, 73, 89], 'B': [90, 99, 56, 61, 79, 97], 'C': [80, 111, 67, 67, 83, 101]}
0
ответ дан Mehrdad Dowlatabadi 17 January 2019 в 02:06
поделиться
Другие вопросы по тегам:

Похожие вопросы: