如何将列表与列表中的常见元素合并?

时间:2019-03-26 01:32:39

标签: python list merge

我正在尝试将所有列表合并到具有共同元素的列表中。我有一些工作代码。但是,在此示例上似乎无法使用:

from flask import Flask, render_template, url_for, redirect, request, jsonify, Response
import requests
import simplejson as json

app = Flask(__name__)

@app.route('/forecast/', methods=['POST','GET'])
def forecast():
    error=''

    if request.method=="POST":

        a=request.form.get('given_date')

        pred_value=requests.get('http://localhost:5001/forecast/'+str(a))
        if pred_value:


            return Response(pred_value)

        return jsonify({'error': 'Missing data'})

    return render_template('sample.html', error=error)

if __name__=='__main__':
    app.run(debug=True, port=5000)

输入为:

<!DOCTYPE html>
<html>
<head>
    <title>WEATHER API</title>  
</head>
<br>
<br>
<br>
<hr>
<body>
<form action="{{url_for('forecast')}}" method="POST">
    <label>DATE</label>
    <input type="text" name="given_date" id="given_date">
    <button class="btn btn-lg btn-primary btn-block" type="submit">Enter </button>
    <br>
    <br>
    <hr>

      <div id="result"/>
    </form> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script src="../static/jquery-3.0.0.js"></script>
    <script src="text/javascritpt">
        $(document).ready(function(){
            $('submit').on('click',function(event){
                event.preventDefault();
                var $result = $('#result')
                $.ajax({
                    type:'GET',
                    url:'/forecast/',
                    data:$('given_date')
                    dataType:'JSON'
                    success: function(result){
                         $('#result').append(JSON.stringify(result))
                    }

                }) 

             })

         })
        </script>

</body> 
</html>

我的结果是:

def merge_subs(lst_of_lsts):
    res = []
    for row in lst_of_lsts:
        for i, resrow in enumerate(res):
            if row[0]==resrow[0]:
                res[i] += row[1:]
                break
            else:
                res.append(sorted(row))
    return sorted(res)

但我应该得到:

merge_subs([[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]])

2 个答案:

答案 0 :(得分:1)

我同意@ Ajax1234,可以使用递归(特别是尾部递归)解决此问题:

def merge(lists, results=None):

    if results is None:
        results = []

    if not lists:
        return results

    first = lists[0]
    merged = []
    output = []

    for li in lists[1:]:
        for i in first:
            if i in li:
                merged = merged + li
                break
        else:
            output.append(li)

    merged = merged + first
    results.append(list(set(merged)))

    return merge(output, results)

结果如下:

>>> lists = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
>>> merge(lists)
[[1, 3, 5, 7], [0, 2, 4, 6]]

答案 1 :(得分:0)

您需要使用递归:

geom_linerange()

输出:

def group(d, _start, _c = [], _seen = [], _used=[]):
  r = [i for i in d if any(c in _start for c in i) and i not in _seen and i not in _used]
  if not r:
    yield set(_c)
    for i in d:
      if i != _start and i not in _used:
         yield from group(d, i, _c=[], _seen=[], _used=_used+[i, *r])
  else:
    yield from group(d, _start, _c=_c+[i for b in r for i in b], _seen=_seen+r, _used=_used+r)

data = [[1, 7, 3], [1, 7, 5], [2, 0, 4], [2, 0, 6], [3, 7, 1], [3, 7, 5], [4, 0, 2], [4, 0, 6], [5, 7, 1], [5, 7, 3], [6, 0, 2], [6, 0, 4]]
result = list(map(list, {tuple(i) for i in group(data, data[0], _seen=[data[0]]) if i}))