[英]Access elements from two sublist without using a nested for loop in python
for example:例如:
list = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
and I want to compare the first element of two consecutive sublists in every iteration of for loop.我想在 for 循环的每次迭代中比较两个连续子列表的第一个元素。
How should I write the for loop?我应该如何编写for循环?
I have tried this following code:我已经尝试过以下代码:
for x in list:
print(x[0])
print(x+1[0])
I know the use of ( x+1[0]
) is completely illogical.我知道 (
x+1[0]
) 的使用是完全不合逻辑的。 But what should I use at this place?但是我应该在这个地方使用什么? Any suggestions?
有什么建议么? Like comparing(any type of mathematical comparison) 1st elements of list1 & list2, list3 & list4.
就像比较(任何类型的数学比较)list1 和 list2、list3 和 list4 的第一个元素。
Try:尝试:
for x in list1:
for y in list1:
if x[0] == y[0]:
print(x[0],y[0])
Now if you don't want to compare the same elements (which the above code does):现在,如果您不想比较相同的元素(上面的代码所做的):
for x in list1:
for y in [i for i in list1 if i!=x]:
if x[0] == y[0]:
print(x[0],y[0])
Or you could print like:或者你可以像这样打印:
for x in list1:
for y in [i for i in list1 if i!=x]:
if x[0] == y[0]:
print(x ,"and", y , 'have the same elements first')
Here:这里:
list1 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
You can use zip()
to pair off consecutive lists by passing slices to zip.您可以使用
zip()
通过将切片传递给 zip 来配对连续列表。 To pair them off at an offset like: [0, 1], [1, 2], [2, 3]
you could use:要将它们以如下偏移量配对:
[0, 1], [1, 2], [2, 3]
您可以使用:
zip(l, l[1:])
To pair them off as pairs (rather than repeating the last one like [0, 1], [2, 3]
) you could use:要将它们成对配对(而不是像
[0, 1], [2, 3]
那样重复最后一个),您可以使用:
zip(l[::], [1:1])
In your example that would look like:在您的示例中,如下所示:
l = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
for l1, l2 in zip(l[::2], l[1::2]):
print(l1[0], l2[0])
Prints:印刷:
1 5
9 13
following code will genrate first element from every sublist.以下代码将从每个子列表中生成第一个元素。 Tweak it according to your need
根据您的需要调整它
lst = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
for i in range(len(lst[0])):
for j in range(len(lst)):
print(lst[j][i], end=" ")
print()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.