简体   繁体   中英

Python print item in list gives lots of results

a = [1,2,3]
b = [4,5,6]
#i have 2 lists
for x in a:
 for y in b:
  print x,' vs ',y

Then i got

1 vs 4 , 1 vs 5, 1 vs 6 ,2 vs 4 ... and so on

I need only 3 results :- 1 vs 4 2 vs 5 3 vs 6

Mean 1st item on a with 1st item on b and 2nd with 2nd and 3rd with 3rd Please help me

Try this:

a = [1,2,3]
b = [4,5,6]
[print('{0} vs {1}'.format(x,y)) for (x,y) in zip(a, b)]

Zip will join your two lists into ((1, 4), (2, 5), (3, 6))

The other answers are fine, another approach would be using enumerate.

for i, x in enumerate(a):
    print x," vs ", b[i]

This generates a zipped list of sorts, where each value is paired with its index value in the list. Eg enumerate([1, 2, 3]) => [(0, 1), (1, 2), (2, 3)] .

a = [1,2,3]
b = [4,5,6]

for first, second in zip(a,b):
    print(first, ' vs ', second)

zip ties together the values of a and b . So the first element of zip(a,b) is [1,4] , the next element is [2,5] and so on. Note that zip creates an iterator, so you can't directly access the elements via index ( zip(a,b)[1] doesn't work).

Try this brother:

x = [1, 2, 3]
y = [4, 5, 6]

for i, j in zip(x, y):
print i + " / " + j

It will give you:

1 / 4
2 / 5
3 / 6

Also check: "for loop" with two variables?

Zip would be prefect for your use case.

More about zip: https://docs.python.org/2/library/functions.html#zip

a = [1,2,3]
b = [4,5,6]
for x in zip(a,b):
    print x[0],' vs ',x[1]

Note: If the size of your lists are different then zip stops at the smallest element

谢谢大家zip(a,b)和enumerate(a,b)都工作良好,但是如果我有a = [1,2,3,4]和b = [1,2,3]这样的列表,则zip(a, b)仅工作1,1 2,2 3,3,第4个变量不可见,枚举方法工作良好,但最终给出了超出范围的错误:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM