[英]Comparing each item in list to Other item in other list Python
i got stuck on this code, can you help me?我被这个代码卡住了,你能帮我吗?
a = [1, 2, 3]
b = [4, 5, 6]
item = []
item.append(a)
item.append(b)
for i in range(len(item)):
for j in range(len(item[i])):
print('{} <= {}'.format(item[i][j], item[i+1][j]))
You can use zip
to iterate over lists in parallel:您可以使用zip
并行迭代列表:
for x, y in zip(a, b):
print(f'{x} <= {y}')
# 1 <= 4
# 2 <= 5
# 3 <= 6
If you do it for three lists, It would look like this:如果您为三个列表执行此操作,它将如下所示:
for x,y,z in zip(a,b,c):
print(f"{x} <= {y} <= {z}")
Output:输出:
1 <= 4 <= 7
2 <= 5 <= 8
3 <= 6 <= 9
According to your illustration and assuming that the number of elements is equal on a and b , I believe the approach you are looking for is:根据您的说明并假设a和b上的元素数量相等,我相信您正在寻找的方法是:
a = [1, 2, 3]
b = [4, 5, 6]
for i in range(len(a)):
print(f"{a[i]} <= {b[i]}")
But if you want to obtain the result of the comparisson, you can do:但是如果你想获得比较的结果,你可以这样做:
a = [1, 2, 3]
b = [4, 5, 6]
for i in range(len(a)):
print(f"{a[i]} <= {b[i]} : {a[i] <=b [i]}")
Hopefully this will help you!希望这会帮助你! :D :D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.