Reputation: 1746
I've 2 list in this form:
name = ['John','Jack','Benny', 'Jane']
location = [(219, 459, 374, 304)]
When I'm doing
for (top, right, bottom, left), name in list(zip(location, name)):
print(location, name)
I'm getting the following result:
[(219, 459, 374, 304)] J
But I want to get this result:
[(219, 459, 374, 304)] John
Also, Suppose now my list is the following:
name = ['John','Jack', 'Jane']
location = [(219, 459, 374, 304), (200, 459, 350, 214), (159, 349, 264, 104)]
How to get the result of above for loop in this form:
[(219, 459, 374, 304)] John
[(200, 459, 350, 214)] Jack
[(159, 349, 264, 104)] Jane
Upvotes: 1
Views: 72
Reputation: 113978
I just copied and pasted your example code
>>> name = ['John','Jack', 'Jane']
>>> location = [(219, 459, 374, 304), (200, 459, 350, 214), (159, 349, 264, 104)]
>>> for n,loc in zip(name,location):
... print("%s %s"%(n,loc))
...
John (219, 459, 374, 304)
Jack (200, 459, 350, 214)
Jane (159, 349, 264, 104)
Upvotes: 1
Reputation: 95948
The reason you are getting
[(219, 459, 374, 304)] J
Instead of:
[(219, 459, 374, 304)] John
Is because you reused the name
variable:
for (top, right, bottom, left), name in list(zip(location, name)):
print(location, name)
Thus, when you run this a second time, name
refers to the last name
in your first attempt, presumably 'Jane'
. So the first element is 'J'
since it is iterating over the string.
Be careful with your variable names. And post reproducible examples. If you had try to do this in a fresh process as is suggested, you would have not seen this behavior.
Upvotes: 4
Reputation: 71451
Try this:
from itertools import izip_longest
name = ['John','Jack', 'Jane']
location = [(219, 459, 374, 304), (200, 459, 350, 214), (159, 349, 264, 104)]
new = [i for i in izip_longest(location, name) if None not in i]
izip_longest
is helpful because it will allow you to filter out any occasion of two lists or tuples that do not match in length:
name = ['John','Jack','Benny', 'Jane']
location = [(219, 459, 374, 304)]
new = [i for i in izip_longest(location, name) if None not in i]
print new
Output:
[((219, 459, 374, 304), 'John')]
Upvotes: 2