返回一个列表,其中包含最高数字和最佳值之和的索引

时间:2017-05-15 17:22:34

标签: python

我一直在研究一个函数,它将一个二维列表的nums作为参数,并返回一个列表,其中包含具有最高值总和的行的索引以及这些值的总和。这是我已经得到的。我已经尝试过累加器,如果[i] + 1> i:但是继续获取​​错误消息只能是concnetate list而不是int。我已经尝试在newList中添加j:并且打印出太多的nums。可以有人帮助我。第一年的程序员,真的卡住了。当我使用max error not iterable时。

def FindLargestRow(lsts):
    newList=[]
    for i in lsts:
    newList.append(sum(i))
    return newList

print(FindLargestRow([[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]))
print()

期望的结果是:

启动FindLargestRow [1,15]

5 个答案:

答案 0 :(得分:1)

您可以使用max和index函数:

public static void main(String[] args) throws Exception {
    URL url = App.class.getResource("/ehcache.xml");
    Configuration xmlConfig = new XmlConfiguration(url);

    CacheManager cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
    cacheManager.init();

    Main main = new Main();
    main.bind("cacheManager", cacheManager);

    main.addRouteBuilder(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("timer:foo?period=5s&repeatCount=1")
                .process(exchange ->{
                    Map<String, String> inputMap = new HashMap<>();
                    inputMap.put("name", "murli");
                    inputMap.put("lastname", "hiware");
                    inputMap.put("city", "pune");
                    exchange.getIn().setBody(inputMap);
                    exchange.getIn().setHeader("CamelEhcacheAction", EhcacheConstants.ACTION_PUT_ALL);
                })
                .to("ehcache://testCache?cacheManager=#cacheManager&keyType=java.lang.String&valueType=java.lang.String")
                .process(exchange -> {
                    //here I want to access already created testCache component but it is creating new one.
                    Cache<String, String> cache = cacheManager.getCache("testCache", String.class, String.class);
                    System.out.println("Cache Element:"+cache.get("name"));
                    System.out.println("Exchange Message:"+exchange.getIn().getBody());

                });
        }
    });

    main.run();
}

答案 1 :(得分:1)

您可以将sum()映射到列表并找到最大总和。使用该索引,您可以找到具有最大总和的列表索引。

        <!DOCTYPE html>
<html>
<head>
    <title>Countries</title>
    <meta charset="utf-8" />
    <script src="Scripts/jquery-3.1.1.js"></script> // Tried even with jquery-1.12.4.js
    <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
    <link href="Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
    <link href="Content/bootstrap.min.css" rel="stylesheet" />


</head>
<body>

    <div class="container">

        <table class="table table-bordered table-hover table table-responsive success" id="countriesTable">
            <thead>
                <tr>
                    <th>
                       Country Id
                    </th>
                    <th>
                        Country name
                    </th>

                    <th class="col-md-2">
                       Action
                    </th>
                </tr>
            </thead>
            <tbody class="tbody"></tbody>
        </table>
    </div>
</body>
</html>

 <script type="text/javascript">
        $(document).ready(function () {

            $('#countriesTable').DataTable({
                "bSort": true,
                "bFilter": true,
                "bPaginate": true,
                "bProcessing": true
            });
loadCountries();
}

function loadCountries() {

            $('#compTable').DataTable({
                "bSort": true,
                "bFilter": true,
                "bPaginate": true,
                "bProcessing": true
            });

            $.ajax({
                url: "/Api/Countries",
                type: "GET",

                headers: {

                    'Authorization': 'Bearer ' + sessionStorage.getItem('accessToken')

                },

                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    var html = '';
                    $.each(result, function (key, item) {


                        html += '<tr>';
                        html += '<td>' + item.CountryId + '</td>';
                        html += '<td>' + item.CountryName + '</td>';


                        html += '<td><Button class="btn btn-primary" onclick="return getByID(' + item.CountryId + ')">Edit</button>  <Button                         class="btn btn-danger btn-md" onclick="return Delete(' + item.CountryId + ')">Delete</Button></td>';
                        html += '</tr>';
                    });
                    $('.tbody').html(html);
                },
                error: function (jqXHR) {

                    if (jqXHR.status == "401") {
                        $('#errorModal').modal('show');
                    }
                    else {
                        $('#divErrorText').text(jqXHR.responseText);
                        $('#divError').show('fade');
                    }



                }
            });
        }


  </script>

即,

def FindLargestRow(lsts):
    s=map(sum,lsts)
    return s.index(max(s)),max(s)

答案 2 :(得分:1)

尝试以下操作,使用2D数组来跟踪最高总和:

def FindLargestRow(lsts):
    lengths = []
    for i in lsts:
        lengths.append([i, sum(i)])
    return max(lengths, key=lambda x:x[1])[0] 
>>> print(FindLargestRow([[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]))
[1, 2, 3, 4, 5]

答案 3 :(得分:0)

你可以试试这个:

the_list = [[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4]]

new_list = map(sum, the_list)


return [[i for i in range(len(the_list)) if sum(the_list[i]) == max(new_list)][0], max(new_list)]

答案 4 :(得分:-1)

#!/usr/bin/perl

use strict;
use warnings 'all';

use Data::Dumper;

my $self = bless { }, 'My::Class';

my @files = glob '/tmp/test/*.txt';

for (@files) {
        my $days = int(-M $_);
        my $mins = int((time - (stat $_)[9]) / 60);
        my $item = {
                file  => $_,
                days => $days,
                minutes => $mins
        };
        push @{ $self->{remove} }, $item if $days > 10;
        push @{ $self->{stale} },  $item if $mins > 15;
}

print Dumper $self;

打印(FindLargestRow([[1,2,3],[1,2,3,4,5],[1,2],[1,2,3,4])) print()