Python for循环迭代和访问列表列表

时间:2016-05-09 21:51:54

标签: python arrays for-loop iteration

给出以下代码:

2

我收到错误:array = [[0, 2], [3, 4]] for i in array: print '%d' % i[0][0]

但如果我改为TypeError: 'int' object has no attribute '__getitem__' 我收到错误:print'%d' %i

我应该如何遍历数组并打印每个子数组的第一个和第二个值?

由于

5 个答案:

答案 0 :(得分:2)

i是1维的。因此:

 print '%d' % i[0] 

PS。它不是很清楚你想要的输出是什么。此解决方案将打印每个列表的第一个元素。

答案 1 :(得分:2)

$('input[name="all"]').click(function() {
  var status = $(this).is(':checked');
  alert(status);
  $('input[type="checkbox"]').attr('checked', status);
});

甚至更好:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="main">
  <div class="cat1">Element of category1</div>
  <div class="cat4">Element of category4</div>
  <div class="cat3">Element of category3</div>
  <div class="cat1">Element of category1</div>
  <div class="cat2">Element of category2</div>
</div>

<label>
  <input type="checkbox" name="all" checked="true">
  All / none
</label>
<label>
  <input type="checkbox" name="cat1" checked="true">
  A
</label>
<label>
  <input type="checkbox" name="cat2">
  B
</label>
<label>
  <input type="checkbox" name="cat3">
  C
</label>
<label>
  <input type="checkbox" name="cat4">
  D
</label>

答案 2 :(得分:1)

您想要SELECT account.name, address.first_line FROM account JOIN address ON address.id = account.address_id WHERE account.date_updated >= '2016-05-05 12:00:00' UNION SELECT account.name, address.first_line FROM account JOIN address ON address.id = account.address_id WHERE address.date_updated >= '2016-05-05 12:00:00'

答案 3 :(得分:1)

首先,语句for x in y循环遍历y,并将x分配给您当前正在循环播放的y中的值,例如 y = [1, 2, 3] for x in y: print x 会给出输出:1 2 3 4因此,在你的情况下 array = [[0, 2], [3, 4]] for i in array: print '%d' % i[0][0] """ i is [0, 2] on the first iteration making i[0] = 0 i[0][0] -> TypeError: %d format: a number is required, not list changing this to i would obvious lead to i being a list that you're attempting to assign as a number -> TypeError: %d format: a number is required, not list """

你真正打算做的是停留i[0]制作代码: array = [[0, 2], [3, 4]] for i in array: print '%d' % i[0]

至于你的问题,如何迭代数组并打印值,你可以做类似的事情: array = [[0, 2], [3, 4]] for subarray in array: for element in subarray: print element

答案 4 :(得分:0)

如果你想保持循环,你可以这样做:

array = [[0, 2], [3, 4]]
for i in array:
    print '%d' % i[0]