Reputation: 213
I have a list containing string elements:
movielst = ['A WALK,DRAGONBALL', 'JAMES BOND,MISSION']
and another list that contains integer values:
userlst = [[1,20],[6,7]]
I'm planning to print the output based off both list where the first element in movielst corresponds to the first list in userlst and so on.
Output to get:
Movies: A WALK,DRAGONBALL
Users: 1,20
Movies: JAMES BOND,MISSION
Users: 6,7
I wrote
for j in range(len(userlst)-1):
for i in movielst:
print("Movies: " + str(i))
print("Users: " + str(userlst[j]))
But I'm getting:
Movies: A WALK,DRAGONBALL
Users: 1,20
Movies: JAMES BOND,MISSION
Users: 1,20 #should be 6,7
How do i print the output based off both lists in parallel?
Upvotes: 0
Views: 51
Reputation: 12689
You can try this:
movielst = ['A WALK,DRAGONBALL', 'JAMES BOND,MISSION']
userlst = [[1,20],[6,7]]
for i in zip(movielst,userlst):
print("Movies : {}".format(i[0]))
print("Users : {} {}".format(*i[1]))
output:
Movies : A WALK,DRAGONBALL
Users : 1 20
Movies : JAMES BOND,MISSION
Users : 6 7
Upvotes: 0
Reputation: 104102
Use zip, join, and format with a comprehension:
>>> print '\n'.join("Movies: {}\nUsers: {}".format(x,y) for x,y in zip(movielst,userlst))
Movies: A WALK,DRAGONBALL
Users: [1, 20]
Movies: JAMES BOND,MISSION
Users: [6, 7]
Or, as stated in comments and if you want double spaced:
>>> print '\n\n'.join("Movies: {}\nUsers: {}".format(*z) for z in zip(movielst,userlst))
Movies: A WALK,DRAGONBALL
Users: [1, 20]
Movies: JAMES BOND,MISSION
Users: [6, 7]
Upvotes: 1
Reputation: 350
The j in the first loop will not increase until 'i' traverse through every element, so j will print 1.20 both times. For traversing through both lists at the same time you can use one for loop.
for j in range(len(userlst)):
print("Movies: " + str(movielst[j]))
print("Users: " + str(userlst[j]))
The output will be :
Movies: A WALK,DRAGONBALL
Users: [1, 20]
Movies: JAMES BOND,MISSION
Users: [6, 7]
Upvotes: 0
Reputation: 82805
You can use zip
Ex:
movielst = ['A WALK,DRAGONBALL', 'JAMES BOND,MISSION']
userlst = [[1,20],[6,7]]
for i in zip(movielst, userlst):
print("Movies: {}".format(i[0]))
print("Users: {}".format(", ".join(map(str, i[1]))))
Output:
Movies: A WALK,DRAGONBALL
Users: 1, 20
Movies: JAMES BOND,MISSION
Users: 6, 7
Note:
map
to convert int to string for userlstjoin
to concat the element in userlst to your required format.Upvotes: 1
Reputation: 3648
If you know both lists are the same length:
for i in range(len(movielst)):
print("Movies: {}".format(str(movielst[i]))
print("Users: {}".format(str(userlst[i])))
print(' ')
This way you loop over both loops and print the same index of both lists in the same loop.
The .format works as following:
print('text {} text {}'.format(<first thing>, <second thing>))
outputs:
text <first thing> text <second thing>
Upvotes: 0