简体   繁体   中英

python two for loops in list comprehension with 2 items

I'm trying to comprehend two loops in one line with 2 variables, however it is always returning one variable and I don't seem to understand the reason behind it. My code is as follow:

text = ['hello, hi', 'goodbye, bye', 'how do you do, howdy']
mapped = {x:y for string in text for x, y in string.split(',')}

The error I'm getting:

ValueError: too many values to unpack (expected 2)

How can I adjust my line so that it returns 2 variables instead of one? Or is it just not possible?

I understand that expanded it looks as follows:

for string in text:
  for x, y in string.split(','):
    mapped[x] = y

I don't understand where I'm going wrong.

Look carefully at the order of operations that you really want - and I think you're just missing some brackets:

text = ['hello, hi', 'goodbye, bye', 'how do you do, howdy']
mapped =  {x:y for x, y in [string.split(',') for string in text]}

Works for me.

I found a different way to achieve the same result, but without using double comprehension (which defeats the point in this question). I'm sharing it in case someone wants to know.

dict(string.split(',') for string in text)

since x:y for x, y is redundant it can simply be omitted.

This error arises because string.split() is creating a list, which looks like

['hello', ' hi']
['goodbye', ' bye']
['how do you do', ' howdy']

Now, for x, y in string.split() is useless because there aren't 2 values to assign x and y to. There is only 1 list. You can rather try

for string in text:
    lis = string.split(',')
    mapped.update({lis[0] : lis[1]})

Output

{'goodbye': ' bye', 'hello': ' hi', 'how do you do': ' howdy'}

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