Reputation: 167
I've looked at other answers but it looks like they use 2 different values.
The code:
user = ['X', 'Y', 'Z']
info = [['a','b','c',], ['d','e','f'], ['g','h','i']]
for u, g in user, range(len(user)):
print '|',u,'|',info[g][0],'|',info[g][1],'|',info[g][2],'| \n'
So basically, it needs to output:
'| X | a | b | c |'
'| Y | d | e | f |'
'| z | g | h | i |'
But instead, I get this error:
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
for u, g in user, range(len(user)):
ValueError: too many values to unpack
As far as I know both user and range(len(user)) are of equal value.
Upvotes: 4
Views: 1385
Reputation: 250881
for u,g in user, range(len(user)):
is actually equivalent to:
for u,g in (user, range(len(user))):
i.e a tuple. It first returns the user
list and then range
. As the number of items present in user
are 3
and on LHS you've just two variable (u
,b
), so you're going to get that error.
>>> u,g = user
Traceback (most recent call last):
File "<ipython-input-162-022ea4a14c62>", line 1, in <module>
u,g = user
ValueError: too many values to unpack
You're looking for zip
here(and use string formatting instead of manual concatenation):
>>> user = ['X', 'Y', 'Z']
>>> info = [['a','b','c',], ['d','e','f'], ['g','h','i']]
for u, g in zip(user, info):
print "| {} | {} |".format(u," | ".join(g))
...
| X | a | b | c |
| Y | d | e | f |
| Z | g | h | i |
Upvotes: 14
Reputation: 5199
The following code works too:
>>> for i in zip(user,info):
print i[0],'|',
for x in i[1]:
print x,'|',
print
And I get the output:
X | a | b | c |
Y | d | e | f |
Z | g | h | i |
P.S.:I know there have been a couple of answers, But I just thought this is also a way to get the result and thats why I have added it!
Upvotes: 0
Reputation: 765
>>> g = 0
>>> for u in user:
... print '|',u,'|',info[g][0],'|',info[g][1],'|',info[g][2],'| \n'
... g=g+1
...
| X | a | b | c |
| Y | d | e | f |
| Z | g | h | i |
Upvotes: 1
Reputation: 7062
for u in user:
print '|',u,'|',info[user.index(u)][0],'|',info[user.index(u)][1],'|',info[user.index(u)][2],'| \n'
Upvotes: 2