[英]Updating a 2d list
lis
is a list.Trying to manipulate it as a 2d list and update with some values. lis
是一个列表。尝试将其作为2d列表进行操作并使用某些值进行更新。
lis = [0 for i in range(3)]
print "1st time list",lis
for i in range(3):
lis[i]=[0]*2 # replaced and tried with lis[i]=[0,0]
print "2nd time list ",lis
for i in range(3):
for j in lis[i]:
print "i:",i
print "j:",j
lis[i][j] = i+j
print "value entered: ", lis[i][j] # here showing correct o/p
print lis #should be [[0,0],[1,1],[2,2]] , but not coming
#as expected.
Could anybody explain it and correct me? 有人可以解释一下并纠正我吗?
I'm assuming what you want to do is have every inner list contain the index number as the elements [[0,0],[1,1],[2,2],[3,3] ...]
我假设您想做的是让每个内部列表都包含索引号作为元素[[0,0],[1,1],[2,2],[3,3] ...]
Keeping with the current structure of your code, this should work: 与您的代码的当前结构保持一致,这应该可以工作:
lis = [0 for i in range(3)]
print "1st time list",lis
for i in range(3):
lis[i]=[0]*2 # replaced and tried with lis[i]=[0,0]
print "2nd time list ",lis
for i in range(len(lis)):
lis[i] = [i, i]
print lis
The reason yours wasn't working is because of how you're doing the inner loop. 您无法使用的原因是因为您执行内部循环的方式。 for j in lis[i]
doesnt do what you expect. for j in lis[i]
没有达到您的期望。 What that line does is it takes lis[i] which is a list in itself, and loops through every element in that list. 该行要做的是获取lis [i],它本身就是一个列表,并循环遍历该列表中的每个元素。 At the time of that loop, the last element is 0 so you're always getting a 0 in the final inner list position. 在该循环时,最后一个元素为0,因此最终内部列表位置始终为0。
This is probably a simpler way to achieve what you want (although I don't know if your example is part of a larger project which requires you to do it the way you're currently doing it): 这可能是实现所需目标的更简单方法(尽管我不知道您的示例是否属于较大项目的一部分,而这需要您按照当前的方式进行操作):
numElements = 3
lis = []
for i in range(numElements):
lis.append([i,i])
print lis
Here's a way to populate the list so it ends up with the contents you say you want: 这是一种填充列表的方法,因此最终可以得到您想要的内容:
lis = range(3)
print "1st time list", lis
for i in range(len(lis)):
j = lis[i]
lis[i] = [j, j]
print lis # -> [[0, 0], [1, 1], [2, 2]]
There are shorter and faster ways to do this, but since it's uclear what you're trying to accomplish, I haven't shown them. 有较短和较快的方法可以执行此操作,但是由于您不清楚要完成的工作,因此我没有显示它们。
If you are looking to create something like [[0, 0], [1, 1], [2, 2], ...] 如果您要创建类似[[0,0],[1,1],[2,2],...]的对象
I would do it so, 我会这样做的
print [[i, i] for i in xrange(n)]
Where n is the number of such entries that you want. 其中,n是所需此类条目的数量。 In your first example, n = 3 在第一个示例中,n = 3
You can read more about list comprehensions https://docs.python.org/2/tutorial/datastructures.html 您可以阅读有关列表理解的更多信息https://docs.python.org/2/tutorial/datastructures.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.