无法理解python代码

时间:2015-10-18 09:28:15

标签: python arrays list matrix 2d

问。编写一个带2位数的程序,X,Y作为输入并生成2-   维数组。第i行和第j列中的元素值   数组应该是i * j。

一个。

input_str = raw_input()
dimensions=[int(x) for x in input_str.split(',')]

rowNum=dimensions[0]
colNum=dimensions[1]
multilist = [[0 for col in range(colNum)] for row in range(rowNum)]
for row in range(rowNum):
  for col in range(colNum):
    multilist[row][col]= row*col
print multilist

我想知道multilist = [[0 for col in range(colNum)] for row in range(rowNum)]

中0的含义是什么

1 个答案:

答案 0 :(得分:-1)

在列表推导中,首先,调用它,argument是将在当前迭代位置插入的值。 它可能是任何东西,所以它在这里为零。

这直译为标准:

<html lang="en-US">

<head>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css">
  <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.0/sweetalert.min.css" rel="stylesheet">

  <link rel="icon" href="http://www.mzirafos.lt/favicon.ico" type="image/x-icon" />
  <link rel="shortcut icon" href="http://www.mzirafos.lt/favicon.ico" type="image/x-icon" />

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Mėmelio Žirafos - Facebook feeds page</title>

  <style>
    html {
      overflow-y: scroll;
    }
    header {
      margin-bottom: 50px;
    }
    .progress {
      top: 50%;
      width: 50%;
      margin: 0 auto;
    }
    .event-only .not-event {
      display: none;
    }
    .post-by {
      display: block;
      margin-bottom: 25px;
    }
    .post-date {
      display: block;
    }
    .card .card-content .card-title {
      line-height: 26px;
      margin-bottom: 15px;
      display: inline-block;
    }
    img.responsive-img {
      width: 100%;
    }
  </style>
</head>

<body>

  <div class="progress">
    <div class="indeterminate"></div>
  </div>

  <div class="hide" id="content">
    <!--header-->
    <header>
      <nav class="top-nav">
        <div class="container">
          <div class="nav-wrapper">
            <p>Mėmelio Žirafos Facebook feeds page</p>
          </div>
        </div>
      </nav>
    </header>
    <!--end header-->

    <div class="container">
      <div class="row">
        <!--checkbox to show all posts or events only-->
        <div class="col s6">
          <p>
            <input type="checkbox" id="events-only" />
            <label for="events-only">Show events only</label>
          </p>
        </div>
        <!--end checkbox-->
      </div>
      <div class="row">
        <h3 class="center-align" id="posts-acc-title">Facebook posts</h3>
        <!--posts wrapper-->
        <div class="col s12" id="fb-posts-wrap"></div>
        <!--end posts wrapper-->
      </div>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sugar/1.4.1/sugar.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.0/sweetalert.min.js"></script>
  <script src="https://cdn.rawgit.com/zenorocha/clipboard.js/master/dist/clipboard.min.js"></script>

  <script>
    (function() {

      /*
       * Our Globals
       */

      var html = '';

      var finalData = [];

      var token = 'CAAQYWWjo5zkBAGlqs2AxxsWKcgWEI0VM3UA7555dhCQEOCTu9VW91tpfaNvrt4tS0w8DkxPJHvRENRrMeDT9QC1aSvHdZA7nhw9ZBqZAyUhMM6PTQoJggn7pJRHEO8xQJp8lsGZAqixVU8SvrMlhUUhwmzB11h9ISqd3MvmoD4aVZBPPD1geO';

      var baseURL =
        'https://graph.facebook.com/v2.4/{slug}/feed?fields=picture,created_time,message,link,type,description,caption,full_picture,id,admin_creator,from&limit=50&access_token={token}';

      var slugs = [{
        slug: 'sisaidgallery',
        complete: false
      }, {
        slug: 'duzenos',
        complete: false
      }, {
        slug: 'bbcnews',
        complete: false
      }, {
        slug: 'Klaipeda.renginiai',
        complete: false
      }, {
        slug: 'PORTbyBarBara',
        complete: false
      }, {
        slug: 'Kastonas',
        complete: false
      }, {
        slug: 'klaipedosdramosteatras',
        complete: false
      }, {
        slug: '238899589464193',
        complete: false
      }];

      /*
       * allComplete
       */
      var allComplete = function() {

        for (var i = 0; i < slugs.length; i++) {
          if (slugs[i].complete === false) {
            return false;
          }
        }

        return true;
      };

      /*
       * makeURL
       */
      var makeURL = function(url, token, slug) {
        return url.replace('{token}', token).replace('{slug}', slug);
      };

      /*
       * Date formatter
       */
      var dateFormatter = function(date) {
        var dateFormat = '{HH}:{mm}, {Weekday}, {d} {Month}, {yyyy}';
        return Date.create(date).format(dateFormat);
      }

      /*
       * Mark slug as complete
       */
      var completeSlug = function(mySlug) {
        for (var i in slugs) {
          if (slugs[i].slug === mySlug) {
            slugs[i].complete = true;
          }
        }
      };

      var copyTextID = 100;

      /*
       * template
       */
      var template = '' +
        '<div class="card blue-grey darken-1 hoverable {isEvent}">' +
        '<div class="card-content white-text">' +
        '<span class="post-date">Posted on: {fb-post-date}</span>' +
        '<span class="post-by">Post by: {fb-post-from}</span>' +
        '<div class="row">' +
        '<div class="col s2">' +
        '<img class="responsive-img" src="{fb-image}" alt=""/>' +
        '</div>' +
        '<div class="col s10" id="post-target-{fb-post-id}">' +
        '<span class="card-title">{fb-post-title}</span>' +
        '<p>{fb-post-text}</p>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '<div class="card-action">' +
        '<a target="_blank" href="{fb-post-link}">Open post</a>' +
        '<a class="waves-effect waves-light btn white-text red darken-1 hoverable" data-clipboard-target="#post-target-{fb-post-id}"><i class="material-icons right">subject</i>Copy</a>' +
        '</div>' +
        '</div>';


      /*
       * checking title, text and images
       */

      var replaceUndefined = function(str) {
        return str === undefined ? '' : str;
      };

      var replaceImage = function(str) {
        return str === undefined ? 'https://placehold.it/350x150' : str;
      };

      /*
       * bindTemplate
       */
      var bindTemplate = function(template, obj) {

        return template
          .replace('{isEvent}', obj.type === 'event' ? '' : 'not-event')
          .replace('{fb-image}', replaceImage(obj.picture))
          .replace('{fb-post-from}', obj.from.name)
          .replace('{fb-post-title}', replaceUndefined(obj.description))
          .replace('{fb-post-text}', replaceUndefined(obj.message))
          .replace('{fb-post-link}', obj.link)
          .replace('{fb-post-date}', dateFormatter(obj.created_time))
          .replace(/{fb-post-id}/g, obj.id);

      };

      var makeAjax = function(fbUrl, next, slug) {
        $.ajax({
          url: fbUrl
        }).done(function(data) {
          next(data, slug);
        });
      };

      /*
       * renderTemplate
       */
      var renderTemplate = function() {
        $('#fb-posts-wrap').html(html);
      };

      /*
       * makeAjaxCalls
       */
      var makeAjaxCalls = function(slugs) {

        slugs.forEach(function(slug) {
          makeAjax(makeURL(baseURL, token, slug.slug), showAllPosts, slug.slug);
        });

      };

      /*
       * Flatten data
       */
      var flattenData = function(data) {
        var fullData = [];
        var empty = [];

        data.forEach(function(row) {
          fullData.push(row.data);
        });

        return empty.concat.apply(empty, fullData);
      };

      var compare = function(a, b) {
        if (a.last_nom < b.last_nom) {
          return -1;
        }

        if (a.last_nom > b.last_nom) {
          return 1;
        }

        return 0;
      }

      var showAllPosts = function(data, slug) {

        // Let's first mark this slug as complete
        completeSlug(slug);

        // And store our data
        finalData.push(data);

        if (allComplete()) {

          // merge all data
          var fullData = flattenData(finalData);

          // sort all data and
          var sortedData = fullData.sort(compare);

          // build the html
          sortedData.forEach(function(obj) {
            html += bindTemplate(template, obj);
          });

          // call the renderTemplateFunction
          renderTemplate();

          // finally hide the progress bar
          $('.progress').fadeOut();
          $('#content').removeClass('hide');
        }

      };


      /*
       * Listen to the change in the checkbox
       */
      $('#events-only').change(function() {
        if ($(this).is(':checked')) {
          // hide the non events with css
          $('#fb-posts-wrap').addClass('event-only');
        } else {
          // show the non events with css
          $('#fb-posts-wrap').removeClass('event-only');
        }
      });

      /*
       * Kick off
       */
      makeAjaxCalls(slugs);
    })();
  </script>
</body>

</html>

当您从下到上范围阅读此代码时,列表理解也是如此。

外部列表的第一个“参数”是:

multilist = []
for i in range(rowNum):
    row = []
    for j in range(colNum):
        row.append(0)
    multilist.append(row)

虽然内部列表的第一个“参数”(因此是一个项目)是0。

所以,这个内部列表在外部列表中重复rowNum次:

[0 for j in range(colNum)]

有一种更好的方法:

[ [inner_list] for i in range(colNum)]