使用python将子列表中的第一个元素与同一列表中的元素合并

时间:2018-05-05 10:33:30

标签: python python-3.x list

我在下面有一个列表。我需要使用它来创建一个新的嵌套列表,其中只有子列表中的第一个元素与列表中的最后一个元素。

b=[[a,3],[b,3],[c,3]]

结果应该看起来像

<!DOCTYPE html>
<meta charset="UTF-8">
<style>
  .node circle {
    fill: #fff;
    stroke: steelblue;
    stroke-width: 1px;
  }

  .node text {
    font: 12px sans-serif;
    text-color: white;
  }

  .link {
    fill: none;
    stroke: #ccc;
    stroke-width: 3px;
  }

  body {
    background-image: url("gray.png");
  }
</style>

<body>
  <!-- <script type="text/javascript" src="lib/d3.min.js"></script> -->
  <script src="https://d3js.org/d3.v4.min.js"></script>

  <script>
    var treeData = {
      "name": "HTTP-GET",
      "children": [{
          "name": " http://wah.comsats.edu.pk/ ",
          "children": [{
              "name": " http://fonts.googleapis.com/css?family=Oswald "
            },
            {
              "name": " http://wah.comsats.edu.pk/img/acad.jpg "
            },
            {
              "name": " http://wah.comsats.edu.pk/js/responsiveCarousel.min.js "
            },
            {
              "name": " http://wah.comsats.edu.pk/slides/wahm.jpg "
            },
            {
              "name": " http://wah.comsats.edu.pk/slides/BITA17.jpg "
            },
            {
              "name": " http://wah.comsats.edu.pk/slides/alumni.jpg "
            },
            {
              "name": " http://wah.comsats.edu.pk/img/ann.jpg "
            },
            {
              "name": " http://wah.comsats.edu.pk/img/ann.jpg "
            }
          ]
        },
        {
          "name": " https://www.google.com.pk/search?q=nsut&oq=nsut&aqs=chrome..69i57j69i60l4j69i59.613j0j7&sourceid=chrome&ie=UTF-8 "
        },
        {
          "name": " https://www.google.com.pk/url?sa=t&source=web&rct=j&url=http://www.nsut.com/&ved=0ahUKEwiq-q3goqbaAhXSxqQKHfLhBDIQFggmMAA "
        },
        {
          "name": " https://www.google.com.pk/search?q=nust&oq=nust&aqs=chrome..69i57j0l5.814j0j7&sourceid=chrome&ie=UTF-8 "
        },
        {
          "name": " https://pbs.twimg.com/profile_images/734623083781345280/Kb-33Gf3_normal.jpg "
        },
        {
          "name": " https://pbs.twimg.com/media/DaGZdo6V4AAJ6PW?format=jpg&name=medium "
        },
        {
          "name": " https://www.google.com.pk/search?q=patent&oq=patent&aqs=chrome..69i57j0l5.6101j0j7&sourceid=chrome&ie=UTF-8 "
        },
        {
          "name": " https://syndication.twitter.com/i/jot "
        },
        {
          "name": " https://platform.twitter.com/jot.html "
        },
      ]
    };



    var margin = {
        top: 20,
        right: 90,
        bottom: 30,
        left: 90
      },
      width = 1960 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;
    var svg = d3.select("body").append("svg")
      .attr("width", width + margin.right + margin.left)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" +
        margin.left + "," + margin.top + ")");
    var i = 0,
      duration = 750,
      root;
    var treemap = d3.tree().size([height, width]);
    root = d3.hierarchy(treeData, function(d) {
      return d.children;
    });
    root.x0 = height / 2;
    root.y0 = 0;
    root.children.forEach(collapse);

    update(root);

    function collapse(d) {
      if (d.children) {
        d._children = d.children
        d._children.forEach(collapse)
        d.children = null
      }
    }

    function update(source) {
      var treeData = treemap(root);
      var nodes = treeData.descendants(),
        links = treeData.descendants().slice(1);
      nodes.forEach(function(d) {
        d.y = d.depth * 180
      });

      function colorSwitch(d) {
        console.log("I am in colorSwitch");

        switch (d.data.name) {
          case 'wah.comsats.edu.pk/':
            return "yellow";
            break;
          case 'wah.comsats.edu.pk/AboutCIIT/Introduction.aspx':
            return "green";
            break;
          case 'Pwah.comsats.edu.pk/favicon.ico':
            return "blue";
            break;
          default:
            // console.log('There's something happening in here, what it is ain't exactly clear.');
            return "blue";
            break;
        }
      }

      var node = svg.selectAll('g.node')
        .data(nodes, function(d) {
          return d.id || (d.id = ++i);
        });
      var nodeEnter = node.enter().append('g')
        .attr('class', 'node')
        .attr("transform", function(d) {
          return "translate(" + source.y0 + ", " + source.x0 + ")";
        })
        .on('click', click);
      nodeEnter.append('circle')
        .attr('class', 'node')
        .attr('r', 1e-6)
      // .style("fill", function(d, i) {
      // return d._childern ? "lightsteelblue" : "#fff";
      // .style("fill", "pink");

      nodeEnter.append('text')
        .attr("dy", ".35em")
        .attr("x", function(d) {
          return d.children || d._children ? -13 : 13;
        })
        .attr("text-anchor", function(d) {
          return d.children || d._children ? "end" : "start";
        })
        .text(function(d) {
          return d.data.name;
        });
      var nodeUpdate = nodeEnter.merge(node);
      nodeUpdate.transition()
        .duration(duration)
        .attr("transform", function(d) {
          return "translate(" + d.y + "," + d.x + ")";
        });
      nodeUpdate.select('circle.node')
        .attr('r', 10)
        // return d._children ? "lightsteelblue" : "#fff";
        .style("fill", function(d) {
          switch (d.data.name) {
            case ' http://wah.comsats.edu.pk/ ':
              return "yellow";
              break;
            case ' https://platform.twitter.com/jot.html ':
              return "green";
              break;
            case ' http://wah.comsats.edu.pk/slides/BITA17.jpg ':
              return "blue";
              break;
            default:
              return "#f23567"; //or use hex colors
              break;
          }
        })
        .attr('cursor', 'pointer');
      var nodeExit = node.exit().transition()
        .duration(duration)
        .attr("transform", function(d) {
          return "translate(" + source.y + "," + source.x + ")";
        })
        .remove();
      nodeExit.select('circle')
        .attr('r', 1e-6);
      nodeExit.select('text')
        .style('fill-opacity', 1e-6);
      var link = svg.selectAll('path.link')
        .data(links, function(d) {
          return d.id;
        });
      var linkEnter = link.enter().insert('path', "g")
        .attr("class", "link")
        .attr('d', function(d) {
          var o = {
            x: source.x0,
            y: source.y0
          }
          return diagonal(o, o)
        });
      var linkUpdate = linkEnter.merge(link);
      linkUpdate.transition()
        .duration(duration)
        .attr('d', function(d) {
          return diagonal(d, d.parent)
        });
      var linkExit = link.exit().transition()
        .duration(duration)
        .attr('d', function(d) {
          var o = {
            x: source.x,
            y: source.y
          }
          return diagonal(o, o)
        })
        .remove();
      nodes.forEach(function(d) {
        d.x0 = d.x;
        d.y0 = d.y;
      });

      function diagonal(s, d) {

        path = `M ${s.y} ${s.x}
         C ${(s.y + d.y) / 2} ${s.x},
           ${(s.y + d.y) / 2} ${d.x},
           ${d.y} ${d.x}`

        return path
      }

      function click(d) {
        if (d.children) {
          d._children = d.children;
          d.children = null;
        } else {
          d.children = d._children;
          d._children = null;
        }
        update(d);
      }
    }
  </script>
</body>

2 个答案:

答案 0 :(得分:1)

使用zip()

In [79]: a=[['a','b','c'],3]

In [80]: list(zip(a[0], [a[1]]*len(a[0])))
Out[80]: [('a', 3), ('b', 3), ('c', 3)]

或者:

In [83]: (a, b, c), num = a

In [84]: [(a, num), (b, num), (c, num)]
Out[84]: [('a', 3), ('b', 3), ('c', 3)]

或者更一般:

In [85]: lst, num = a

In [86]: from itertools import repeat

In [87]: list(zip(lst, repeat(num, len(lst))))
Out[87]: [('a', 3), ('b', 3), ('c', 3)]

另一种方法是使用嵌套列表理解:

In [15]: a
Out[15]: [['a', 'b', 'c'], [1, 2]]

In [16]: [(j, i) for i in a[1] for j in a[0]]
Out[16]: [('a', 1), ('b', 1), ('c', 1), ('a', 2), ('b', 2), ('c', 2)]

答案 1 :(得分:1)

您可以使用list comprehension

>>> a = [['a','b','c'], 3]
>>> sublist, value = a
>>> [[x, value] for x in sublist]
[['a', 3], ['b', 3], ['c', 3]]